Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...