Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peculiar behavior of split() of string class [duplicate]

Tags:

java

string

To my understanding following program should print 0,0 as an output.

However, when I run this program I am getting 1,0 as an output.

public class Test1 {
    public static void main(String[] args) {
        System.out.println("".split(";").length); //1
        System.out.println(";".split(";").length);//0
    }
}

Please help me understand what is going on here ?

like image 721
Sachin Sachdeva Avatar asked Oct 17 '17 05:10

Sachin Sachdeva


People also ask

What is split () function in string?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

Does split () alter the original string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string.

What is split () in Java?

Split() String method in Java with examples The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.

What is the return type of split method of string class?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.


1 Answers

relavant code

        // If no match was found, return this
        if (off == 0)
            return new String[]{this};

        // Add remaining segment
        if (!limited || list.size() < limit)
            list.add(substring(off, value.length));
like image 153
Scary Wombat Avatar answered Oct 20 '22 00:10

Scary Wombat