0
String parts[] = formattedString.split("\\:");
String partA = parts[0];
String partB = parts[1];

I'm trying to split a string before and after the ":" symbol.
For example, "Before:After" works, but in the case where there is nothing after the ":" like "Before: " gives me an exception. I've tried to check for null in parts[1] but it still throws exception.

lenignes
  • 333
  • 1
  • 5
  • 17
  • 3
    Check the length of the resulting array. – Wiktor Stribiżew Oct 17 '16 at 07:22
  • The problem here is unrelated to regex. It's that you don't understand arrays. I'm also betting you haven't thought about strings like `"Beginning:Middle:End"`, either. – jpmc26 Oct 17 '16 at 07:24
  • If you know there's a possibility of that don't assume there's going to be something at index 1. – ChiefTwoPencils Oct 17 '16 at 07:25
  • @WiktorStribiżew Thanks a lot! It helped. – lenignes Oct 17 '16 at 07:25
  • The problem is that you need to read the Javadoc of [`String.split`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String))... call `formattedString.split("\\:", -1);` instead. – Andy Turner Oct 17 '16 at 07:25
  • the String you are splitting for (`"\\:"`) looks pretty much like the separator between drive letter and path on windows systems. So why don't go with this to get the drive letter: `File theFile= new File(formattedString); if(theFile.isAbsolute()) String driveLetter=file.getPath().getRoot();` – Timothy Truckle Oct 17 '16 at 07:34

3 Answers3

1

You need to check the length of the array to determine whether anything at index 1 exists before referencing it.

if(parts.length > 1) {
    //do something with it
}
rorschach
  • 2,871
  • 1
  • 17
  • 20
1

The length of the array that the split method gives is determined by the number of elements that could be splitted.

This means that if you don't have a second element, the length of the array will be 1 instead of 2.

You should check the length of the array to determine if there is a second element.

1
String parts[] = formattedString.split("\\:");
String partA = parts[0];
String partB = parts[1];

Into above code you want to access index 0 and 1 so please check first the array parts have these index or not. before accessing these index please check the length of array.

Jay Prakash
  • 787
  • 6
  • 22