-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSplitExample.java
More file actions
48 lines (36 loc) · 1.1 KB
/
SplitExample.java
File metadata and controls
48 lines (36 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* 31. How to split string in java Program.
*/
public class SplitExample {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("=== String Split Program ===");
while (true) {
System.out.print("\nEnter the sentence (type 'exit' to quit): ");
String input = scan.nextLine().trim();
// Exit condition
if (input.equalsIgnoreCase("exit")) {
System.out.println("Program terminated.");
break;
}
System.out.print("Enter the split character/string: ");
String split_val = scan.nextLine().trim();
// Validation
if (split_val.isEmpty()) {
System.out.println("Delimiter cannot be empty. Try again.");
continue;
}
// Safe split (handles regex special characters)
String[] result = input.split(Pattern.quote(split_val));
System.out.println("\nSplit Result:");
for (String r : result) {
System.out.println(r);
}
}
} catch (Exception e) {
System.out.println("Unexpected error occurred: " + e.getMessage());
}
}
}