Is it always safe to use the first element of the array returned by split?

I am sure that the answer is yes, but I just want to confirm that there is never a situation where a nonempty string (no matter what it contains) returns anything other than a valid string as the first member of the array returned by split.

In other words.

String foo = ""; // or "something" or "abc" or any valid string at all String[] bar = foo.split(",")[0]; 

My understanding is that the bar will never be empty, and the destination bar cannot fail. If the delimiter is not found in the string, it simply returns the whole foo as the first element of the returned array.

+6
source share
4 answers

No, He may fail

ArrayIndexOutOfBound failed if foo =","

+9
source

(1) If foo is a direct match for the regular expression pattern, the array returned from split is 0 and foo.split[0] will foo.split[0] ArrayIndexOutOfBoundsException .

(2) Keep in mind String.split may raise a PatternSyntaxException if the regular expression is invalid at runtime.

+1
source

Yes. bar will be equal to the string ""

.split (",") tries to break the comma, but there is no comma in the original string, so the original string will be returned.

Which would be harder:

 String s = ",,,,,,," String[] sarray = s.split(","); 

Here sarray [0] will return an ArrayIndexOutOfBoundsException.

+1
source

Here is a set of test cases for you that demonstrate above:

 public class Test { public static void main(String[] args){ test("x,y"); test(",y"); test(""); test(","); } private static void test(String x){ System.out.println("testing split on value ["+x+"]"); String y = x.split(",")[0]; if(null == y){ System.out.println("x returned a null value for first array element"); } else if(y.length() < 1) { System.out.println("x returned an empty string for first array element"); } else { System.out.println("x returned a value for first array element"); } } } 

At startup, you get:

 $ javac Test.java && java Test testing split on value [x,y] x returned a value for first array element testing split on value [,y] x returned an empty string for first array element testing split on value [] x returned an empty string for first array element testing split on value [,] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Test.test(Test.java:11) at Test.main(Test.java:6) 
+1
source

Source: https://habr.com/ru/post/910946/


All Articles