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?
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.
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.
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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With