-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathStringTokens.java
More file actions
42 lines (34 loc) · 1.07 KB
/
StringTokens.java
File metadata and controls
42 lines (34 loc) · 1.07 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
import java.io.*;
import java.util.*;
public class StringTokens {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter: ");
String s = scan.nextLine();
// Trim leading/trailing whitespace
s = s.trim();
// Check if the string is empty after trimming
if (s.isEmpty()) {
System.out.println(0);
scan.close();
return;
}
// Split the string by one or more non-alphabetic characters
String[] tokens = s.split("[^a-zA-Z]+");
// Count and print valid tokens (non-empty strings)
int count = 0;
for (String token : tokens) {
if (!token.isEmpty()) {
count++;
}
}
System.out.println(count);
// Print each valid token
for (String token : tokens) {
if (!token.isEmpty()) {
System.out.println(token);
}
}
scan.close();
}
}