java.lang.StringIndexOutOfBoundsException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12317716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.StringIndexOutOfBoundsException
提问by Ali Ahmad
This a code for converting hex to string but it works fine until size of the string doesn't exceeds 62 characters?
这是一个用于将十六进制转换为字符串的代码,但它可以正常工作,直到字符串的大小不超过 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: String index out of range: 62 at java.lang.String.substring(Unknown Source) at HEX.hexToString(HEX.java:36) at HEX.main(HEX.java:56)
java.lang.StringIndexOutOfBoundsException: String index out of range: 62 at java.lang.String.substring(Unknown Source) at HEX.hexToString(HEX.java:36) at HEX.main(HEX.java:56)
采纳答案by Santosh
You will face this problem only when you have odd number of characters in your string. Fix your function as follows:
只有当您的字符串中有奇数个字符时,您才会遇到这个问题。修复您的功能如下:
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());
}
回答by gefei
i+2
in String str = hex.substring(i, i+2);
is the problem. even if i < hex.length()
, i+2
is too large if hex.length()
is odd.
i+2
在String str = hex.substring(i, i+2);
是问题。即使i < hex.length()
,i+2
如果hex.length()
是奇数就太大了。
回答by Andrei0427
If youre using String.length in a for loop with i initiated at 0 then you need to -1 from the strings length
如果您在 for 循环中使用 String.length 且 i 以 0 启动,则您需要从字符串长度中取 -1
for (int i = 0; i < hex.length()-1; i+=2)
回答by Drona
Fix your loop condition :
修复您的循环条件:
for (int i = 0; i < hex.length() - 3; i +=2)