Java String.split()用法注意点

split()方法是String类中较为常用的一个方法,用来分割字符串并返回一个字符串数组。

1.注意分隔的特殊字符

例如. 以及| 等等要注意转义字符的正确使用:

String str1 = "aa.bb.cc.dd";
String[] res1 = str1.split("\\.");   //结果是 aa bb cc dd 必须要对 . 进行转义

String str2 = "aa|bb|cc|dd";
String[] res2  =str2.split("|");

2.分隔为字符串

常规使用方法:

String str3 = "hello newworld";
        String[] res3 = str3.split("new");

3.多个分隔符的情况

在API的介绍中split函数是使用正则方式进行匹配的,例如这种多个匹配情况:

String str4 ="aaand bborcc";
String[] res4 = str4.split("and|or");

这里要分隔 and 或者 or 中间使用或符号就可以了。

暂时这么多,想到再补充。

猜你喜欢

转载自blog.csdn.net/sinat_34328764/article/details/80166368