Java How to split a string
By:Roy.LiuLast updated:2019-08-17
To split a string, uses String.split(regex). Review the following examples :
String phone = "012-3456789"; String[] output = phone.split("-"); System.out.println(output[0]); System.out.println(output[1]);
Output
012 3456789
Note
This split (regex) takes a regex as an argument, remember to escape the regex special characters, like period/dot.
This split (regex) takes a regex as an argument, remember to escape the regex special characters, like period/dot.
1. Split a Period / dot
The period / dot is a special character in regex, you have to escape it either with a double backlash \\. or uses the Pattern.quote method.
TestSplit.java
package com.mkyong.test import java.util.regex.Pattern; public class TestSplit { public static void main(String[] args) { String test = "abc.def.123"; String[] output = test.split("\\."); //alternative //String[] output = test.split(Pattern.quote(".")); System.out.println(output[0]); System.out.println(output[1]); System.out.println(output[2]);
Output
abc def 123
Some common checking before split.
TestSplit.java
package com.mkyong.test import java.util.regex.Pattern; public class TestSplit { public static void main(String[] args) { String test = "abc.def.123"; if(test.contains(".")){ String[] output = test.split("\\."); if(output.length!=3){ throw new IllegalArgumentException(test + " - invalid format!"); }else{ System.out.println(output[0]); System.out.println(output[1]); System.out.println(output[2]); }else{ throw new IllegalArgumentException(test + " - invalid format!");
2. StringTokenizer example
In the old days, Java developers like to use the StringTokenizer class to split a string. This is because the StringTokenizer class is available since JDK 1.0 and the String.split() is available since JDK 1.4
TestSplit.java
package com.mkyong.test import java.util.StringTokenizer; public class TestSplit { public static void main(String[] args) { String test = "abc.def.123"; StringTokenizer token = new StringTokenizer(test, "."); while (token.hasMoreTokens()) { System.out.println(token.nextToken());
Output
abc def 123
Note
This StringTokenizer is a legacy class, retained for compatibility reasons, the use is discouraged! Please use string.split().
This StringTokenizer is a legacy class, retained for compatibility reasons, the use is discouraged! Please use string.split().
References
From:一号门
COMMENTS