How split() method works in java?

Ashutosh Tiwari :

My question is why the following program:

// Java program to demonstrate working of split(regex,
// limit) with high limit.
public class GFG
{
    public static void main(String args[])
    {
        String str = "geekss@for@geekss";
        String [] arrOfStr = str.split("s", 5);
    }
}

splits the string "geekss@for@geekss" into 5 substrings:{"geek", "", "@for@geek", "", ""}. According to me there should be 4 substrings:{"geek", "","@for@geek", ""}. Can someone clarify my doubt?

Sweeper :

If you look carefully at the docs:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

So your resulting array contains two things:

  • a substring of your string which is followed by s (italic part)
  • whatever is left at the end of your string (bold part)

The reason you got {"geek", "", "@for@geek", ""} for the first four elements is because they are followed by s. The last "" you got is what is left after matching every s.

Note that the limit argument of 5 you passed is also related. As per the docs:

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

So the last matched delimiter is the s at the very end. After that there is still an empty string that it haven't checked.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476981&siteId=1