如何使用if条件检查字符串的结尾是否已在Java中到达

时间:2017-01-06 06:55:06

标签: java

我是Java的新手,我需要一个替换字符串中的单词的程序。它的工作正常,除了我无法到达字符串末尾的部分。 我的代码

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter string");
original = keyboard.nextLine();
System.out.println("Enter word");
word = keyboard.next();
System.out.println("Enter new word");
omit = keyboard.next();
length = original.length();
for (i= 0; i< length; i++) {
    c = original.charAt(i);
    if (c != ' ') {
       nword = nword + c;
    }
    else {
       if (nword.equals(word)) {
           nword = omit;
       }
       nword = nword + " ";
       duplicate = duplicate + nword;
       nword = "";
    }           
}
System.out.print(duplicate);
keyboard.close();

此处,除非字符串末尾有空格,否则字符串中的最后一个单词不会添加到nword。如何检查字符串original

的结尾

1 个答案:

答案 0 :(得分:0)

我认为在for循环之后,您需要在其他部分中使用代码的变体来将最后一个单词附加到duplicate。类似的东西:

   if (nword.equals(word)) {
       nword = omit;
   }
   // don’t append a space this time
   duplicate = duplicate + nword;

未经测试。