为什么在一个数组的第0个索引中,将一个拆分()w/o分隔符?

时间:2022-05-08 22:03:46
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String str="aaabbddaabbcc";
    String[] str2=str.split("");
    String pointer=str2[0];
    int count=0;
    String finalStr="";
    for(String str132:str2)
    {
        if(str132.equalsIgnoreCase(pointer))
        {
            ++count;
        }
        else
        {

            finalStr+=str132+count;
            count=0;
            pointer=str132;
            ++count;
        }
    }
    System.out.println(finalStr);
}

On performing a str.split(""), why am I getting a "" in the 0th index of the str2 array?

在执行string .split(“”)时,为什么我在str2数组的第0个索引中得到了一个“”?

1 个解决方案

#1


2  

why am i getting a "" in the 0th index of the str2 array?

为什么我在str2数组的第0个索引中得到一个“”?

Because the delimiter you use has matched here:

因为你使用的分隔符在这里是匹配的:

 aaaabbddaabbcc
^

Since .split() collects the parts is has "walked by" when it progresses into the string, here it collects the empty string.

从.split()收集到的部分是“经过”的,当它进入字符串时,在这里它收集空字符串。

Note also that since the delimiter is empty, in order to avoid infinite loops, at the next iteration, .split() will forward one character before starting to search again.

还要注意,由于分隔符是空的,为了避免无限循环,在下一个迭代中,.split()将在开始搜索之前转发一个字符。

#1


2  

why am i getting a "" in the 0th index of the str2 array?

为什么我在str2数组的第0个索引中得到一个“”?

Because the delimiter you use has matched here:

因为你使用的分隔符在这里是匹配的:

 aaaabbddaabbcc
^

Since .split() collects the parts is has "walked by" when it progresses into the string, here it collects the empty string.

从.split()收集到的部分是“经过”的,当它进入字符串时,在这里它收集空字符串。

Note also that since the delimiter is empty, in order to avoid infinite loops, at the next iteration, .split() will forward one character before starting to search again.

还要注意,由于分隔符是空的,为了避免无限循环,在下一个迭代中,.split()将在开始搜索之前转发一个字符。