繁体   English   中英

为什么这个 Java 代码会给出“字符串索引超出范围”错误?

[英]Why does this Java code give an " String index out of range " error?

它显示以下错误: java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:6

我似乎找不到问题所在。

// 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;
        
        }

这一行似乎是问题所在:

if(strs[ind].charAt(i)==strs[j].charAt(i))

i基于索引ind处字符串的 Len,然后用于索引j处的字符串,该字符串的长度可能不同,从而导致错误。

暂无
暂无

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

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