java.lang.StringIndexOutOfBoundsException: String index out of range: 3
privatestaticStringsoundexCoding2(StringsoundexCoding){intindex=1;StringsoundexCoding...
private static String soundexCoding2(String soundexCoding){
int index=1;
String soundexCoding2=soundexCoding.substring(0,1);
while (index < soundexCoding.length()){
char i =soundexCoding.charAt(index);
char j =soundexCoding.charAt(index+1);
if (i==j){
soundexCoding2 = soundexCoding2 + soundexCoding.substring(index,index+1);
index +=2;
}
else{
soundexCoding2 = soundexCoding2 + soundexCoding.substring(index,index+1);
index ++;
}
}
return soundexCoding2;
} 展开
int index=1;
String soundexCoding2=soundexCoding.substring(0,1);
while (index < soundexCoding.length()){
char i =soundexCoding.charAt(index);
char j =soundexCoding.charAt(index+1);
if (i==j){
soundexCoding2 = soundexCoding2 + soundexCoding.substring(index,index+1);
index +=2;
}
else{
soundexCoding2 = soundexCoding2 + soundexCoding.substring(index,index+1);
index ++;
}
}
return soundexCoding2;
} 展开
2个回答
展开全部
最基本的错误是
while (index < soundexCoding.length()-1)
因为你在循环里用了
char j =soundexCoding.charAt(index+1);
看不出来你这段代码的实际用途
我猜你是想消除重复字符吧
private static String delRepeat(String inputStr){
String outputStr=inputStr.substring(0, 1);
char flag1=inputStr.charAt(0);
for(int i=1;i<inputStr.length();i++){
char flag2=inputStr.charAt(i);
if(flag1!=flag2){
outputStr=outputStr+flag2;
}
flag1=flag2;
}
return outputStr;
}
while (index < soundexCoding.length()-1)
因为你在循环里用了
char j =soundexCoding.charAt(index+1);
看不出来你这段代码的实际用途
我猜你是想消除重复字符吧
private static String delRepeat(String inputStr){
String outputStr=inputStr.substring(0, 1);
char flag1=inputStr.charAt(0);
for(int i=1;i<inputStr.length();i++){
char flag2=inputStr.charAt(i);
if(flag1!=flag2){
outputStr=outputStr+flag2;
}
flag1=flag2;
}
return outputStr;
}
追问
你说对了 不过我还是不能理解我哪里错了 求讲解
追答
关键是你程序中的这句
if (i==j){
soundexCoding2 = soundexCoding2 + soundexCoding.substring(index,index+1);
index +=2;
}
如果与上一个字符相同,跳过这个字符写入下一字符
如果遇到"aaa”,那么后边的两个a只能消除一个
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询