Java String Index Out of Bounds Exception

I'm getting the following exception on the line where head is assigned and I'm not sure why:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 44

When using "{1,2},3" as the value of s, running a debugger I can follow the loop and it is correctly assigning commaSpot to be 5 as I think it should. But for some reason s.charAt(commaSpot)) doesn't think 5 is a valid index even though s is 7 characters long.

int commaSpot = 0;
int bracePairs = 0;
for(int i = 0; i < s.length(); i++) {
   if(s.charAt(i) == '{') bracePairs++;
   if(s.charAt(i) == '}') bracePairs--;
   if(s.charAt(i) == ',' && bracePairs == 0) {
      commaSpot = i;
      break;
   }
}
head = s.substring(0, s.charAt(commaSpot));
tail = s.substring(s.charAt(commaSpot), s.length());
Jon Skeet
people
quotationmark

The problem is that you're using the result of s.charAt(commaSpot) as the second argument - rather than commaSpot itself. You want:

head = s.substring(0, commaSpot);
tail = s.substring(commaSpot, s.length());

You don't care about the value of the string at commaSpot - or rather, you know that it's a comma (Unicode value 44, hence the exception message). You care about the value of commaSpot itself, which is the place you want to split on.

people

See more on this question at Stackoverflow