java.lang.StringIndexOutOfBoundsException

时间:2012-09-07 12:02:13

标签: java string indexoutofboundsexception

这是一个将十六进制转换为字符串的代码,但它在字符串大小不超过62个字符之前一直正常工作?

public static String hexToString(String hex)
        {       
           StringBuilder output = new StringBuilder();
           for (int i = 0; i < hex.length(); i+=2)
           {
            String str = hex.substring(i, i+2);
            output.append((char)Integer.parseInt(str, 16));
           }
           return(output.toString());
        }
  

java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:   62                 at java.lang.String.substring(Unknown Source)                 在HEX.hexToString(HEX.java:36)                 在HEX.main(HEX.java:56)

4 个答案:

答案 0 :(得分:3)

i+2中的{p> String str = hex.substring(i, i+2);是问题所在。即使i < hex.length()i+2过大,如果hex.length()为奇数。

答案 1 :(得分:2)

只有在字符串中包含奇数个字符时,才会遇到此问题。修复您的功能如下:

public static String hexToString(String hex)
    {       
       StringBuilder output = new StringBuilder();
       String str = "";
       for (int i = 0; i < hex.length(); i+=2)
       {

        if(i+2 < hex.length()){
            str = hex.substring(i, i+2);
        }else{
            str = hex.substring(i, i+1);
        }
        output.append((char)Integer.parseInt(str, 16));
       }
       return(output.toString());
    }

答案 2 :(得分:0)

如果你在for循环中使用String.length,我从0开始,那么你需要从字符串长度-1开始

for (int i = 0; i < hex.length()-1; i+=2) 

答案 3 :(得分:0)

修复你的循环条件:

for (int i = 0; i < hex.length() - 3; i +=2)