Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why split function behave like this in java?

Tags:

java

if I do

    String a = ""
    String b = a.split(" ")[0];

It is not giving ArrayIndexOutOfBoundException

but when I do

    String a = " "
    String b = a.split(" ")[0];

It is giving me ArrayIndexOutOfBoundException

again when I do

    String a = " abc"
    String b = a.split(" ")[0];

It is not giving me Exception WHY SO?

like image 955
pankaj4u4m Avatar asked Oct 05 '11 13:10

pankaj4u4m


People also ask

What does split () does in Java?

The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

What is the purpose of the split () function?

The split() function can be used to split a given string or a line by specifying one of the substrings of the given string as the delimiter. The string before and after the substring specified as a delimiter is returned as the output.

What is difference between Split and substring in Java?

Split("|"c) , you'll get an array as {"Hello", " world"} . . substring is used to get part of the string at a starting index through a specified length. For example, to get “ello” out of “Hello| world”, you could use "Hello| world".

How does split work on strings in Java?

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.


1 Answers

It's kind of weird.

Thing is, in your first example, the empty String "" is a String, not null. So when you say: Split this "" with the token " ", the patterns doesn't match, and the array you get is the original String. Same as if you did

String a = "abc";
String b = a.split(" ")[0];

The pattern to split doesn't match, so you get one token, the original String.

You get an exception on the second case because the COMPLETE content of your String is exactly the delimiter you've passed to split, so you end up with an empty array.

Let me know if you want some further details, but this is pretty much it.

like image 153
pcalcao Avatar answered Sep 21 '22 18:09

pcalcao