Reputation: 1
I want to know how can we separate words of a sentence where delimiter is be a ' '(space) or '?' or '.'. For ex
Input: THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS
.
Output:
THIS
IS
A
STRING
PROGRAM
IS
THIS
EASY
YES
IT
IS
Upvotes: 0
Views: 86
Reputation: 7804
Refer to the constructor of the StringTokenizer class in Java. It has provision to accept custom delimiter.
Try this:
StringTokenizer tokenizer = new StringTokenizer("THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS", " .?");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextElement());
}
Upvotes: 1
Reputation: 2691
public static void main(String[] args) {
String str = "THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by space ------");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
Upvotes: 0