2014-12-02 36 views
1

我无法让我的程序生成我想要的确切输出。我的程序当前将删除用户输入的句子中的任何一个字符串实例(例如:句子 - 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 
+0

我现在不能检查这个代码自己,但有一个理由使用与相关的一切'end'?假设你没有使用'end',那么会发生什么?在'while'循环中,您可以在给定单词之前和之后得到字符串中出现的所有字符,然后查找字符串中该单词的下一个索引。为什么那么糟糕? – spoko 2014-12-02 14:22:39

回答

4

你的问题是结束,因为指数yindexOf(x,y)支票的x发生。这是int indexOf(String str, int fromIndex)

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, 0); //this line must be 0 or nothing 
} 
+0

非常感谢!不知道这将是一个这样简单的修复。我现在感觉有点愚蠢。 – Smith 2014-12-02 14:30:12

+0

@史密斯不要觉得愚蠢,试着去学习;) – Lrrr 2014-12-02 15:54:43

0

replaceAll()方法由字符串形式提供应该更换给定字的出现的所有字符串

实施例:

sentence.replaceAll("there","") 

sentence.removeAll("there") 
+0

是的,我知道这一点,但我们的老师不希望我们使用这个功能。她希望我们在使用它之前了解其背后的方法。 – Smith 2014-12-02 14:20:15

+0

嗨,请使用stringtokenizer来查找字符串中字的出现并将其删除。使句子字符串缓冲区 – 2014-12-02 14:23:49

+0

While(sentence.indexof(word)){ – 2014-12-02 14:29:39