索引越界异常字符串8

时间:2016-11-09 04:31:27

标签: java string indexoutofboundsexception

我正在尝试设置一个压缩算法,在字符串中的char之前放置一个数字,然后可以连续看到该char。 EX:用于字符串 “balloonnnnns”它会被压缩为“ba2l2o5n”,但我收到索引超出界限错误:

for(int i = 0; i < (length-1); i++ ){
    if (original.charAt(i) == original.charAt(i + 1)){
        count = count + 1; 
        original = original.substring(i, i+1);
        System.out.println(original);
        System.out.println(count); 
        if(count > 0){
            altered = count + original.substring(i);
            System.out.println(altered);
        }
    }else{
        count = 0;

2 个答案:

答案 0 :(得分:2)

正如@Jon Skeet指出的那样,你不应该在循环中改变原作。 您可以尝试这种方式(对代码的评论以便理解)

测试:

public class Test
{

    public static void main ( String [ ] args )
    {
        String original = "balloonnnnns";
        int length = original.length ( );
        int count = 1;
        String altered = "";
        //Loop over all string
        for(int i = 0; i < (length-1); i++ ){
            //while they are the same
            while (original.charAt(i) == original.charAt(i + 1)){
                //count and keep going on the original string
                count++;
                i++;
                //avoid border case when last character is repeated, i.e : baaaaaaaa
                if ( i == length -1)
                {
                    break;
                }
            }
            //if they are repetead
            if(count > 1)
            {
                //add altered + count + charRepeated, i.e. a3e5t
               altered = altered +count + original.charAt(i);

            }
            else{
                //just add the normal character without count
                altered += original.charAt(i);
            }
            //add last character if not repeated
            if ( (i == length - 2) && (count > 1))
            {
                altered += original.charAt ( i+1 );
            }

            //reset counting 
            count = 1;

        }
        System.out.println ( altered );
    }
}

输出:

  

ba2l2o5ns

答案 1 :(得分:0)

第一次执行循环时,您会更新名为&#39; original&#39;与实际&#39;原始&#39;的第一个字符串。 例如。如果String original =&#34; aaa&#34; - 循环执行0后,原始值变为&#39; a#39;!

您可以参考此解决方案: Java compressing Strings

相关问题