1
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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
user3296744
  • 169
  • 3
  • 9

1 Answers1

2

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.

fge
  • 119,121
  • 33
  • 254
  • 329
  • Is it me, or in Java 8 this behaviour changes and first empty String is also removed? – Pshemo Mar 28 '14 at 16:28
  • Confirm for java8, there is no empty string at index 0 :/ – A4L Mar 28 '14 at 16:29
  • @A4L In Java 7 this is well known issue/behaviour, so your confirm is kind of false. But I can't reproduce this problem with JDK 8 and Eclipse Kepler. – Pshemo Mar 28 '14 at 16:31
  • @Pshemo, I confirmed for java8, my java7 test was wrong since I had only compiler compliance setup to 1.7 in my sandbox project, forgot that I replaced the jdk7 with jdk8 :/ ... thanks for pointing that though. – A4L Mar 28 '14 at 16:35
  • 1
    @Pshemo Yes you're right and if i'm not wrong it has been specified in the doc of `split(regex, limit)` which was not present in JDK 7: _"When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring."_ – Alexis C. Mar 28 '14 at 16:40
  • @ZouZou And that solves the case. Now I don't need to create separate question about it :) Or what the hell. I will post my question in few minutes. You can provide this as an answer. – Pshemo Mar 28 '14 at 16:44
  • When there is a "positive-width" match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A "zero-width match" at the beginning however never produces such empty leading substring. Can anyone explain the phrases in "".Am new to java!! – user3296744 Mar 28 '14 at 16:50
  • @user3296744 See [this](http://stackoverflow.com/questions/22718744/why-does-split-in-jdk-8-sometimes-removes-empty-strings-if-they-are-at-start-of/22718904) for further explanation. – Alexis C. Apr 15 '14 at 20:51