[英]Why does this Java code give an " String index out of range " error?
It shows the following error: java.lang.StringIndexOutOfBoundsException: String index out of range: 6它显示以下错误: java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:6
I can't seem to find the problem.我似乎找不到问题所在。
// given an array of strings strs, we need to find the longest common prefix
int ind=0,min=strs[0].length();
// to find the minimum length string
for(int i=0;i<strs.length;i++)
if(min>strs[i].length())
ind=i;
int len=strs[ind].length(),count=0,n=0;
// to check each character of the string having minimum length with the rest of the strings in the array
for(int i=0;i<len;i++)
{
for(int j=0;j<strs.length;j++)
{
if(strs[ind].charAt(i)==strs[j].charAt(i))
count++;
}
if(count==strs.length)
n++;
// n indicates the length of the portion of the string that is common to all (from the left side)
count=0;
}
This line appears to be the issue:这一行似乎是问题所在:
if(strs[ind].charAt(i)==strs[j].charAt(i))
i
is based on the Len of the string at index ind
and then it's used on the string at index j
which may not be the same length causing the error. i
基于索引ind
处字符串的 Len,然后用于索引j
处的字符串,该字符串的长度可能不同,从而导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.