gpt4 book ai didi

java - 索引越界异常字符串 8

转载 作者:行者123 更新时间:2023-12-02 03:14:32 25 4
gpt4 key购买 nike

我正在尝试设置一种压缩算法,当可以连续看到该字符时,该算法会在字符串中的字符之前放置一个数字。 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;

最佳答案

正如 @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

关于java - 索引越界异常字符串 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com