Java - 字符串索引超出界限异常

时间:2013-09-25 16:50:01

标签: java string indexoutofboundsexception

我在分配了头部的行上遇到以下异常,我不确定原因:

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

当使用“{1,2},3”作为s的值时,运行调试器我可以按照循环进行正确分配commaSpot为5,因为我认为应该。但由于某些原因,s.charAt(commaSpot))并不认为5是有效索引,即使s长度为7个字符。

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());

2 个答案:

答案 0 :(得分:5)

问题是你使用s.charAt(commaSpot)的结果作为第二个参数 - 而不是commaSpot本身。你想要:

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

您不关心commaSpot处字符串的值 - 或者更确切地说,您知道它是逗号(Unicode值44,因此是异常消息)。您关心commaSpot本身的价值,这是您要拆分的地方。

答案 1 :(得分:2)

在这些行中

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

s.charAt(commaSpot)会返回char,该int作为索引位置的i处理。您希望使用实际索引commaspot,因此请保留并使用该值的副本({{1}})。

相关问题