2

JS - Split( ) 的用法

 2 years ago
source link: https://segmentfault.com/a/1190000040767335
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

split()方法详解

1.split()主要是用于对一个字符串进行分割成多个字符串数组。标准形式为String [] strings = str.split("");

2.split()方法中括号中的参数可以为一个也可以为多个,每个参数之间用|隔开。并且每个参数之间要紧挨着|。

 如:String [] strings = string.split(" |,|\\?");这里有三个参数:空格、逗号、问号。

3.像?.(点)((正括弧))(反括弧)*(星号)|(竖线)等特殊符号都要在其前面加上\。

4.str.split("");使用默认的情况下,split()方法对每个字符进行分割。

5.当遇到连续的分隔符的时候

String s = "a,b,###c"

String[] ss = s.split(",|#");

system.out.println(ss.length);

打印的结果是:6
ss = {{"a"},{"b"},{""},{""},{""},{"c"}};

为什么会出现3个空字符串呢?因为split当遇到分隔符的时候,就一直读取下一个字符直到遇到不是分隔符的字符为止。

这里当遇到b后面的“,”的时候,会接着读取后面的3个“#”知道遇到c为止。它会把第一个“,”去掉,然后用三个“”去代替3个“#”。

注意:这里在程序中要把ss字符串数组中的“”去掉不能用==来判断而要用equals()来判断。因为这里的字符串数组是在运行时产生的,他存放在堆区,不是在常量池中。

6.

System.out.println("cd:ef::".split(":").length);//末尾分隔符全部忽略
System.out.println("cd:ef::".split(":",-1).length);//不忽略任何一个分隔符
System.out.println(StringUtils.split("cd:ef::",":").length);//最前面的和末尾的分隔符全部都忽略,apache commons
System.out.println(StringUtils.splitPreserveAllTokens("cd:ef::",":").length);//不忽略任何一个分隔符 apache commons


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK