2013-06-25 64 views
0
String weatherLocation = weatherLoc[1].toString(); 
weatherLocation.replaceAll("how",""); 
weatherLocation.replaceAll("weather", ""); 
weatherLocation.replaceAll("like", ""); 
weatherLocation.replaceAll("in", ""); 
weatherLocation.replaceAll("at", ""); 
weatherLocation.replaceAll("around", ""); 
test.setText(weatherLocation); 

weatherLocation仍含有 「像」爲什麼不替換這行代碼中的所有工作?

回答

12

字符串是不可改變的。方法String#replaceAll()將創建一個新的字符串。您需要將結果重新分配回變量:

weatherLocation = weatherLocation.replaceAll("how",""); 

現在,由於replaceAll方法返回修改後的字符串,也可以鏈單行多個replaceAll電話。事實上,這裏不需要replaceAll()。當你想要替換匹配正則表達式模式的子串時,它是必需的。簡單地使用String#replace()方法:

weatherLocation = weatherLocation.replace("how","") 
           .replace("weather", "") 
           .replace("like", ""); 
+0

該死的,太慢了^^ – luk2302

+6

此外,完全錯了:) –

+0

我失敗了完全與我的答案,是 - 刪除它。 – luk2302

6

正如羅希特夏爾Jain說,字符串是不可變;在你的情況下,你可以將呼叫連接到replaceAll以避免多重影響。

String weatherLocation = weatherLoc[1].toString() 
     .replaceAll("how","") 
     .replaceAll("weather", "") 
     .replaceAll("like", "") 
     .replaceAll("in", "") 
     .replaceAll("at", "") 
     .replaceAll("around", ""); 
test.setText(weatherLocation); 
1

我認爲,更好的將是使用StringBuilder/StringBuffer,如果你需要更換大量的字符串文本。爲什麼?正如Rohit Jain寫道String是不可變的,因此每個replaceAll方法都需要創建新的對象。與String不同,StringBuffer/StringBuilder是可變的,所以它不會創建新的對象(它將在同一個對象上工作)。

您可以在此Oracle教程http://docs.oracle.com/javase/tutorial/java/data/buffers.html中閱讀有關StringBuilder的示例。

+0

問題是'StringBuffer' /'StringBuilder'沒有'replaceAll'方法。 –

+0

當然,你是對的,但這並不意味着你不能在StringBuffer/StringBuilder中替換字符串。你可以使用'replace'方法。 – pepuch

+0

您可以使用http://stackoverflow.com/a/3472705/393487 –

2

準確的講,羅希特Jain說,而且,因爲採用的replaceAll,而不是鏈接調用正則表達式,你可以簡單地這樣做

test.setText(weatherLocation.replaceAll("how|weather|like|in|at|around", ""));