0
我是Java的新手,我需要一个替换字符串中的单词的程序。它的工作很好,除了我不能达到弦尾的部分。 我的代码如何使用if条件检查字符串的末尾是否已达到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
为什么不使用'String.replace()'?这是功课吗? – shmosel
'System.out.print(original.replace(word,omit));' – 4castle
对于这类问题,您可能应该删除扫描器并使用静态字符串。这将更容易阅读。你应该解释你的意思是__字符串original_ – AxelH