why a “” in the 0th index of an array on perfoaming a split() w/o delimiters?

南笙酒味 提交于 2020-01-19 15:30:05

问题


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:


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.



来源:https://stackoverflow.com/questions/22718096/why-a-in-the-0th-index-of-an-array-on-perfoaming-a-split-w-o-delimiters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!