2014-12-02 53 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