Split String with .(dot) character java android-ThrowExceptions

Exception or error:

Hello friends i have string like

Android_a_b.pdf

i want to split it like Android_a_b and pdf

i try following code like

String s="Android_a_b.pdf"; 
String[] parts = s.split(".");
String part1 = parts[0];  
String part2 = parts[1];  

when i run above code it give me error like

11-05 09:42:28.922: E/AndroidRuntime(8722): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

at String part1 = parts[0]; line

any idea how can i solve it?

How to solve:

You need to escape . using \

Eg:

String s="Android_a_b.pdf";
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];

Now it will split by .

Split(regex) in Java

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.

Keep in mind that

Parameters:
regex – the delimiting regular expression

Leave a Reply

Your email address will not be published. Required fields are marked *