28

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?

Kirtan
  • 1,782
  • 1
  • 13
  • 35

1 Answers1

85

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

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • It's also important to note that your error points out there is nothing in your Array. If you try to access [0] and get an index out of bounds then you can safely assume that there is something wrong with the split. – B Rad Nov 05 '14 at 04:18
  • Exactly. Unescaped, the `"."` matches every character, so every character is a delimiter and the result of the split consists entirely of empty strings, none of which are included in the return value. – Ted Hopp Nov 05 '14 at 04:18
  • Pattern.quote will make your life easier: s.split(Pattern.quote(".")); (use import java.util.regex.Pattern) – P Kuijpers Oct 20 '17 at 11:28
  • When we have a input like "12.34..." split length is still 2. But if we have "12.34...5" split length is 5. Seems like when a number ends with more dot, that is not considered. But in my case I need that to be considered in length. Any Idea? – Swathi Apr 09 '19 at 06:07