作用
java中String的split()是我们经常使用的方法,用来按照特定字符分割字符串,返回是一个数组
JDK说明
public String[] split(String regex)
//Splits this string around matches of the given regular expression.
注意事项
- 参数regex是一个 regular-expression的匹配模式而不是一个简单的String,对一些特殊的字符(正则表达式中的匹配符)可能会出现你预想不到的结果
例如
String[] ary1 = "a|b|c".split("|");//输入错误的结果 a|b|c
String[] ary2 = "a|b|c".split("\\\\|"); 这样才能得到正确的结果
- 在一个字符串中有多个分隔符,可以用“|”作为连字符
例如
//分隔字符串 “name=? and age =? or sex=?”
String s = "name=? and age =? or sex=?";
String ary = s.split("and|or");
- split之后会去掉该数组最后的所有空字符串
例如
@Test
public void t52()
{
String str = "1,2,3,";
String[] ary = str.split(",");
System.out.println(ary.length);// out put 3
}
备注:此处根据length 判断长度时需要特别注意
- 第二个参数int limit 是要输入一个数值,这个数值n如果 >0 则会执行切割 n-1次,也就是说执行的次数不会超过输入的数值次.数组长度不会大于切割次数
例如
@Test
public void t53()
{
String str = "1,2,3,";
String[] ary = str.split(",",2);
System.out.println(ary.length);// out put 2, 不会超过第二个参数设定的值
}
閱讀更多 新猿易碼 的文章
關鍵字: Java