您的位置:首页 > 编程语言 > Java开发

Java – How to split a string

2015-09-29 09:45 405 查看
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.

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()
.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: