您的位置 首页 php

Java String.split你不知道的4件事

作用

java 中String的split()是我们经常使用的方法,用来按照特定字符分割字符串,返回是一个数组

JDK说明

public String[] split(String regex)

//Splits this string around matches of the given regular expression.

注意事项

  1. 参数regex是一个 regular-expression的匹配模式而不是一个简单的String,对一些特殊的字符( 正则表达式 中的匹配符)可能会出现你预想不到的结果

例如

String[] ary1 = “a|b|c”.split(“|”);//输入错误的结果 a|b|c

String[] ary2 = “a|b|c”.split(“\\|”); 这样才能得到正确的结果

  1. 在一个字符串中有多个分隔符,可以用“|”作为连字符

例如

//分隔字符串 “name=? and age =? or sex=?”

String s = “name=? and age =? or sex=?”;

String ary = s.split(“and|or”);

  1. split之后会去掉该数组最后的所有空字符串

例如

@Test

public void t52()

{

String str = “1,2,3,”;

String[] ary = str.split(“,”);

System.out.println(ary.length);// out put 3

}

备注:此处根据length 判断长度时需要特别注意

  1. 第二个参数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 String.split你不知道的4件事

文章地址:https://www.zhihuclub.com/77292.shtml

关于作者: 智云科技

热门文章

网站地图