gpt4 book ai didi

Java子字符串错误: String index out of range

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:42 26 4
gpt4 key购买 nike

我正在做学校的作业。我试图弄清楚如何从用户给出的字符串中获取单个单词。就我而言,单词始终由空格分隔。所以我的代码计算有多少个空格,然后生成子字符串。如果可以的话请帮忙。

        System.out.print("Please enter a sentence: ");
String userSentence=IO.readString();

String testWord="";
int countSpaces=0;


for(int j=0; j<userSentence.length(); j++){
if((userSentence.charAt(j))==' '){
countSpaces++;

}
}


for(int i=0; i<userSentence.length(); i++){
if(countSpaces>0){

while(userSentence.charAt(i)==' '){
i++;
countSpaces--;
}

testWord=userSentence.substring(i, userSentence.indexOf(" "));
i=i+(testWord.length()-1);

}

if(countSpaces==0){
testWord=userSentence.substring(i);
i=userSentence.length();
}

System.out.print(testWord);

最佳答案

如果我们不必计算空格,下面的代码会更清晰,但我假设这是你的约束,所以我正在使用它。 (编辑:向 JohnG 致敬,因为有比更改 i 更好的方法来解决这个问题)

问题在于 userSentence.indexOf("") 函数将始终返回 ""第一个找到的位置,并且由于您不断递增 i 但不对 userSentence 进行任何更改,substring(i, userSentence.indexOf("")) 命令不再有意义。

上述问题的解决方案是声明一个 remainder 字符串,用于跟踪找到下一个 testWord 后剩余的 userSentence 部分。

另一个需要注意的是,如果没有找到 "" 的出现,indexOf() 将返回 -1,在本例中这意味着您正在执行最后一个单词。在这种情况下,testWord 的 会被设置为 remainder 的末尾。

这就是我所得到的。再说一次, super 笨重,但我试图不重写你所拥有的一切:

    System.out.print("Please enter a sentence: ");
String userSentence=IO.readString();

String testWord="";
int countSpaces=0;

for(int j=0; j<userSentence.length(); j++){
if((userSentence.charAt(j))==' '){
countSpaces++;
}
}

for(int i=0; i<userSentence.length(); i++){
while(i<userSentence.length() && userSentence.charAt(i)==' '){
i++;
countSpaces--;
}
if(i<userSentence.length()){
String remainder = userSentence.substring(i);

if(countSpaces==0){
testWord=userSentence.substring(i);
i=userSentence.length();
} else {
remainder = userSentence.substring(i);
int endOfWordIndex = remainder.indexOf(" "); // set end of word to first occurrence of " "
if(endOfWordIndex == -1){ // if no " " found,
endOfWordIndex = remainder.length(); // set end of word to end of sentence.
}

testWord=remainder.substring(0, endOfWordIndex);
i=i+(testWord.length()-1);
}

System.out.println("word: '" + testWord + "'");

关于Java子字符串错误: String index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40391482/

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