简体   繁体   English

使用string.split时的ArrayIndexOutOfBounds

[英]ArrayIndexOutOfBounds when using string.split

This problem has kept me frustrated for a few days now. 这个问题让我沮丧了几天。 I am using string split to find the second half of a string. 我正在使用字符串拆分来查找字符串的后半部分。 Here is my code: 这是我的代码:

   String pieces[] = piece.split(before[x]);
   piece = piece.split(before[x])[1];

In debug mode i have determined that piece = 在调试模式下,我确定了piece =

<area shape="circle" coords="329,152,13" href="#g35" alt="" onmouseover="return overlib\('&lt;b>Southeast False Creek&lt;/b>&lt;br>215 West 1st Avenue' , SNAPX, 20, SNAPY, 20\);" onmouseout="return nd\(\);"/>

and before[x] = before[x] =

<area shape="circle" coords="329,152,13" href="#g35" alt="" onmouseover="return overlib\('&lt;b>

For some reason I am getting an ArrayIndexOutOfBounds exception with split saying an index of one is invalid. 由于某种原因,我收到了ArrayIndexOutOfBounds异常,但split说索引1无效。 I dont know why this is happening so any help would be greatly appreciated! 我不知道为什么会这样,所以任何帮助将不胜感激!

If you are trying to get the second half of the string useing piece.split(before[x])[1] and its throwing an exception, then obviously it means that your string array piece.split(before[x]) does not have a second element. 如果您尝试使用piece.split(before[x])[1]来获取字符串的piece.split(before[x])[1]并抛出异常,那么显然这意味着您的字符串数组piece.split(before[x])不会有第二个要素。 What you should do is try using piece.split(Pattern.quote(before[x])) and then check the number of strings in the array. 您应该做的是尝试使用piece.split(Pattern.quote(before[x])) ,然后检查数组中的字符串数。 If its more than 1 then you can get the 2nd half of the string using piece.split(Pattern.quote(before[x]))[1] . 如果其大于1,则可以使用piece.split(Pattern.quote(before[x]))[1]获得字符串的第二部分。

Read this for more details http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html#quote(java.lang.String ) 请阅读此内容以获取更多详细信息http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html#quote(java.lang.String

String.split use regular expression to split String into pieces. String.split使用正则表达式将String拆分为多个部分。 "before[x]" contains regular special characters (ie "\\"), so you need to escape these special characters. “ before [x]”包含常规特殊字符(即“ \\”),因此您需要转义这些特殊字符。 refer http://www.regular-expressions.info/reference.html for special character lists 有关特殊字符列表,请参见http://www.regular-expressions.info/reference.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM