In this example, we will obtain two different methods to split a string in Java.
Source Code
1) Using java.util.StringTokenizer
package com.beginner.examples;
import java.util.StringTokenizer;
public class StringSplitExample1 {
public static void main(String[] args){
String string = "ac9BG,RN,7e3,tgfi";
StringTokenizer str = new StringTokenizer(string, ".");
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}
Output:
ac9BG
RN
7e3
tgfi
2) Using String.split()
package com.beginner.examples;
public class StringSplitExample2 {
public static void main(String[] args){
String string = "ac9BG,RN,7e3,tgfi";
String[] strs = string.split(",");
for(String str:strs)
{
System.out.println(str);
}
}
}
Output:
ac9BG
RN
7e3
References
Imported packages in Java documentation: