Ad

Java Split With Unknown Result

- 1 answer

for the following code,

  1. why there is empty string in position 2,3,5,6,8?

  2. then why "b", ":andf", "1" has no empty string behind?

    String[] splitStrs = "booo:and:fooo1o".split("o", -1);  
    System.out.println(splitStrs.length);  
    for (int i=0; i<splitStrs.length; i++) {  
        System.out.println("\"" + splitStrs[i]+ "\"");  
    }

output is:

8
"b"
""
""
":and:f"
""
""
"1"
""

Ad

Answer

Public String [ ] split ( String regex, int limit ) Parameters:

regex – a delimiting regular expression

Limit – the resulting threshold

The limit parameter can have 3 values:

  • limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.
  • limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.
  • limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.

please visit GeeksforGeeks site for more information regarding spliting.

"booo:and:fooo1o".split("o", -1);

why there is empty string in position 2,3,5,6,8?

Since the limit is -1 we can split it any number of times. When 'o' is used as the regex it will give all the values which are before it since there is no value it returns empty string

then why "b", ":andf", "1" has no empty string behind?

There is no empty string because there are characters after the 'o' previous match.

See this example:

class Split{
    public static void main(final String ... $){
        var out = System.out;
        final String s = "ooa";
        for(final String str : s.split("o", -1))
            out.println("\""+str+"\"");

    }
}

Output:

$ javac Split.java && java Split
""
""
"a"

Why this output?

When first match happens @ index 0 which is also the very first character and it returns string before it but since there is no string it returns an empty string.

Then when second match happens with o @ index 1 it returns the string after the first match and before index 1. Since there is no characters it returns an empty string.

After that it returns a.

Ad
source: stackoverflow.com
Ad