2014-12-04 146 views
4

給定兩個字符串base和remove,返回基本字符串的一個版本,其中刪除字符串的所有實例都已被刪除(不區分大小寫)。您可能會認爲刪除字符串的長度爲1或更多。只刪除不重疊的實例,所以用「xxx」刪除「xx」留下「x」。如何刪除部分字符串

withoutString("Hello there", "llo") → "He there" 
withoutString("Hello there", "e") → "Hllo thr" 
withoutString("Hello there", "x") → "Hello there" 

爲什麼我不能使用此代碼:

public String withoutString(String base, String remove) 
{ 
    base.replace(remove, ""); 
    return base; 
} 
+7

我沒有得到,爲什麼人們投票了這個問題..:P – 2014-12-04 12:37:50

回答

8

base.replace不改變原有String例如,由於String是不可變的類。因此,您必須返回replace的輸出,這是一個新的String

 public String withoutString(String base, String remove) 
     { 
      return base.replace(remove,""); 
     } 
4

String#replace()返回一個新的字符串,不會改變它被調用的字符串,因爲字符串是不可變的。在代碼中使用此:

base = base.replace(remove, "")

0

更新您的代碼:

public String withoutString(String base, String remove) { 
    //base.replace(remove,"");//<-- base is not updated, instead a new string is builded 
    return base.replace(remove,""); 
} 
0

嘗試下面的代碼

public String withoutString(String base, String remove) { 
      return base.replace(remove,""); 
     } 

對於輸入:

base=Hello World 
remove=llo 

輸出:

He World 

更多關於這種string操作參觀this鏈接。

0

Apache Commons庫已經實現了這個方法,你不需要再次寫入。

代碼:

return StringUtils.remove(base, remove);