why a “” in the 0th index of an array on perfoamin

2019-01-20 06:00发布

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?

1条回答
The star\"
2楼-- · 2019-01-20 06:18

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

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.

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.

查看更多
登录 后发表回答