您的位置:首页 > 其它

String.split()应该怎么用?

2016-09-08 20:19 302 查看
在java.lang包中有String.split()方法,返回是一个数组。

“.”和“|”都是转义字符,必须得加”\”;

对于“.”是这样的:

public class test1 {

public static void main(String[] args) {
String str = "ABC.DEF";
String[] value = str.split("\\.");
for(String s : value){
System.out.println(s);
}
}
}


输出结果是这样的:



对于“|”,如果是下面这样的,那就错了,看看运行效果:

public class test1 {

public static void main(String[] args) {
String str = "ABC|DEF";
String[] value = str.split("|");
for(String s : value){
System.out.println(s);
}

}

}
![这里写图片描述](http://img.blog.csdn.net/20160908200245759)

是不是,那就已经不是你想要的了,应该下面这样写:


public class test1 {

public static void main(String[] args) {
String str = "ABC|DEF";
String[] value = str.split("\|");
for(String s : value){
System.out.println(s);
}

}


}



如果分隔符是“\”,那我们写的时候必须是这样String str = “ABC\DEF”;分隔符应该这样写

public class test1 {

public static void main(String[] args) {
String str = "ABC\\DEF";
String[] value = str.split("\\\\");
for(String s : value){
System.out.println(s);
}

}

}




|在java正则表达式就是一个特殊字符。\在Java字符串是特殊字符。

所以|是不能表达普通字符|在split()方法的。只能转义2次 。

String.split方法(以及其它类似的需要使用正则表达式的场合)

常见的需要回避“找抽”的字符有: , \ | ^ * + ? ( ) { } [ ] 等等

如果实在想用的话,在split之类需要正则表达式的地方,必须采用转义:

\\ = 转义后的 \

\. = 转义后的 .

\, = 转义后的 ,

\| = 转义后的 |

\^ = 转义后的 ^

\* = 转义后的 *
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string