2017-07-05 133 views
0

我嘗試用另一個字符替換字符以及字符串中的所有字符。在匹配子串後替換字符串的所有後續字符

這是我的代碼到目前爲止。

String name = "Peter Pan"; 
name = name.replace("er", "abc"); 
Log.d("Name", name) 

的結果應該是: 「Petabc」

我將高度讚賞在這個問題上的任何幫助!

+0

'replace()'只會替換你傳遞的參數,在你的情況下,'呃'。 – luizfzs

+0

如果結果應該是** Petabc **,那麼你的代碼爲** name.replace輸出了什麼(「er」,「abc」)**?什麼調試給你? – ShayHaned

+0

@ShayHaned調試發出「Petabc Pan」 – LoveCoding

回答

1

才達到你的目標的一種方式:

  • 搜索字符串,要替換
  • 使用該索引並使用字符串#子繩剪斷
  • 添加sequnce首次出現的將序列替換爲剛創建的子串的末尾

fin。

祝你好運。

編輯

在代碼中它可能是這樣的(未測試)

public static String customReplace(String input, String replace) 
{ 
int index = input.indexOf(replace); 

if(index >= 0) 
{ 
    return input.substring(index) + replace; //cutting string down to the required part and adding the replace 
} 
else 
    return null; //String 'input' doesn't contain String 'replace' 
} 
+0

謝謝,它現在確實工作:) – LoveCoding

0

你可以在這裏使用正則表達式與內置replaceAll方法String的非常容易做你想要什麼:

original.replaceFirst(toReplace + ".*", replaceWith); 

例如:

String original = "testing 123"; 
String toReplace = "ing"; 
String replaceWith = "er"; 
String replaced = original.replaceFirst(toReplace + ".*", replaceWith); 

之後,replaced將被設置爲"tester"

相關問題