我无法让我的程序生成我想要的确切输出。我的程序当前将删除用户输入的句子中的任何一个字符串实例(例如:句子 - Hello there
- 要删除的字符串Hello
和输出there
)。删除Java程序中的单词
我想要做的是添加别的东西,以便程序将删除用户想省略的字符串的任何和所有实例(例如:在我当前的程序中为Hello there there
,它会输出Hello there
。我想要什么它只是打印Hello
)。有人可以给我任何想法如何实现这一点。谢谢!
(IM还相当新的编码,所以如果你有一个输入我的代码是,请随时纠正)
这里是我当前的代码:
import java.util.Scanner;
public class RemoveWord
{
Scanner scan = new Scanner(System.in);
String sentence;
String word;
public void removing()
{
System.out.println("Please enter a sentence");
sentence = scan.nextLine();
System.out.println("Please enter a word you would like removed from the sentence");
word = scan.nextLine();
int start = sentence.indexOf(word), end=0;
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, end);
}
System.out.println(sentence);
}
}
public class RemoveWordR
{
public static void main(String[]args)
{
RemoveWord r1 = new RemoveWord();
r1.removing();
}//main
}//class
我现在不能检查这个代码自己,但有一个理由使用与相关的一切'end'?假设你没有使用'end',那么会发生什么?在'while'循环中,您可以在给定单词之前和之后得到字符串中出现的所有字符,然后查找字符串中该单词的下一个索引。为什么那么糟糕? – spoko 2014-12-02 14:22:39