Split String in Java
There are two ways to split string in Java.
- Using String.split(regex) method.
- Using StringTokenizer class.
Let us see how we can split the string in both ways.
1) Split String using String.split(regex) method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.code2succeed.string; public class SplitStringExample { public static void main(String[] args) { String str = "String split example in java, code2succeed"; //Split String by space System.out.println(" *** Split by space *** "); String [] elements = str.split("\\s"); for(String element : elements) { System.out.println(element); } //Split String by comma(,) System.out.println(" *** Split by comma *** "); elements = str.split(","); for(String element : elements) { System.out.println(element); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
*** Split by space *** String split example in java, code2succeed *** Split by comma *** String split example in java code2succeed |
2) Split String using StringTokenizer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.code2succeed.string; import java.util.StringTokenizer; public class TokenizerExample { public static void main(String[] args) { String str = "String Tokenizer example in java, code2succeed"; StringTokenizer tokenizer = new StringTokenizer(str); System.out.println(" *** Default tokenizer : Split by space *** "); while(tokenizer.hasMoreElements()) { System.out.println(tokenizer.nextElement()); } System.out.println(" *** Split by comma *** "); StringTokenizer tokenizer2 = new StringTokenizer(str, ","); while(tokenizer2.hasMoreElements()) { System.out.println(tokenizer2.nextElement()); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
*** Split by space *** String split example in java, code2succeed *** Split by comma *** String split example in java code2succeed |