我嘗試用另一個字符替換字符以及字符串中的所有字符。在匹配子串後替換字符串的所有後續字符
這是我的代碼到目前爲止。
String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
的結果應該是: 「Petabc」
我將高度讚賞在這個問題上的任何幫助!
我嘗試用另一個字符替換字符以及字符串中的所有字符。在匹配子串後替換字符串的所有後續字符
這是我的代碼到目前爲止。
String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
的結果應該是: 「Petabc」
我將高度讚賞在這個問題上的任何幫助!
才達到你的目標的一種方式:
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'
}
謝謝,它現在確實工作:) – LoveCoding
你可以在這裏使用正則表達式與內置replaceAll
方法String
的非常容易做你想要什麼:
original.replaceFirst(toReplace + ".*", replaceWith);
例如:
String original = "testing 123";
String toReplace = "ing";
String replaceWith = "er";
String replaced = original.replaceFirst(toReplace + ".*", replaceWith);
之後,replaced
將被設置爲"tester"
。
'replace()'只會替換你傳遞的參數,在你的情況下,'呃'。 – luizfzs
如果結果應該是** Petabc **,那麼你的代碼爲** name.replace輸出了什麼(「er」,「abc」)**?什麼調試給你? – ShayHaned
@ShayHaned調試發出「Petabc Pan」 – LoveCoding