2013-08-06 36 views
1

我正在使用android。我有一個包含大量數據的字符串。在該字符串中,我想將特定字符替換爲另一個字符。我得到了我想要替換的角色的索引。但我無法取代那個角色。 我該怎麼做?如何替換android中特定索引處的字符?

String str = "data1data2mdata2test1test2test3dd" 

int ind = str.indexOf("m"); 
System.out.println("the index of m" + ind); 

現在在上面的字符串中,我想將字符「m」(在data2之後)替換爲「#」。

現在我該如何將m替換爲#。請幫助我解決這個問題。

+1

不要忘了搜索第一:HTTP:/ /stackoverflow.com/questions/6952363/java-replace-a-character-at-a-specific-index-in-a-string – noKid

回答

2

您可以使用substring

String newStr = str.substring(0, ind) + '#' + str.substring(ind + 1); 
2

試試這個: str = str.replaceFirst("m", "#");

它將取代第一米至#

2
String str1 = "data1data2mdata2test1test2test3dd" 

    String str = str1.replace("m", "#"); 
    System.out.println(str); 
+0

'replace'返回一個新字符串,它是用newChar替換此字符串中出現的所有oldChar 。 –

+0

Yaa Boris我忘了在這裏提到,它可以通過這樣的方式來實現:StringBuilder str = new StringBuilder(「data1data2mdata2test1test2test3dd」); str.setCharAt(9,'#'); System.out.println(str); –

0

所以你得到10系統出來, 所以這樣你可以取代它,

Str.replace('m', '#')--->when you want all occurrences of it to replace it, 

或者,如果你只想要第一次出現由#替換那麼你可以做下面的技巧,

StringBuffer buff=new StringBuffer(); 
buff.append(Str.substring(0,ind)).append("#").append(Str.substring(ind+1)); 

我希望這將有助於

相關問題