如何從字符串中刪除單詞?例如,如果我有以下輸入:如何從Java中的字符串中刪除單詞?
Cancer is a fatal disease
Cancer is afataldisease
Cancer is a fataldisease
Cancer is afataldisease
Cancer is a fatal disease
Cancer is afataldisease
Cancer is a fataldisease
Cancer is afataldisease
和輸出應該是:
Cancer is a disease(for first 4 cases)
而對於剩餘:
Cancer is a disease
Cancer is a disease
Cancer is a disease
Cancer is a disease
我都想要的輸出爲第4案件,但不是最後4以上。在最後4種情況下,刪除單詞後會留下額外的空格。
String deleteWord(String sentence,String... words)
{
for(String s:words)
{
sentence=sentence.replaceAll(s," ");
}
return sentence;
}
使用String.replaceAll(「word」,「」)'方法有什麼問題。 –
使用一些正則表達式('\\ s'來匹配空格) – 2017-07-30 17:11:01
@OmarAhmed它爲上面的最後4個案例提供了冗餘空間 – hhj8i