2016-03-05 216 views
0

我想只替換一個字符串的一個字符。但是,只要字符在字符串中出現多次,所有這些字符都將被替換,而我只希望替換特定字符。例如:替換字符串的單個字符

String str = "hello world"; 
    str = str.replace(str.charAt(2), Character.toUpperCase(str.charAt(2))); 
    System.out.println(str); 

給出結果:

heLLo worLd 

,而我希望它是:

heLlo world 

我能做些什麼來實現這一目標?

+1

請參閱此鏈接瞭解如何解決這個問題的方法:http://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string – slashNburn

回答

0

替換將不起作用,因爲它將替換字符串中的所有出現。 replaceFirst將無法​​正常工作,因爲它總是會刪除 的第一個匹配項。

由於字符串不可變,所以無論哪種方式,都需要創建一個新的字符串。可以通過以下任一方式完成。

  • 使用子串,並手動創建所需的字符串。

    int place = 2; 
    str = str.substring(0,place)+Character.toUpperCase(str.charAt(place))+str.substring(place+1); 
    
  • 將字符串的字符數組,更換要使用索引的字符,然後轉換陣列回字符串。

0

您應該使用StringBuilder而不是String來實現此目標。

0

replace(char, char)將更換指定的char的所有出現,不僅索引的char。從documentation

返回一個新字符串,該字符串由newChar替換此字符串中的所有oldChar。

你可以做這樣的事情

String str = "hello world"; 
String newStr = str.substring(0, 2) + Character.toUpperCase(str.charAt(2)) + str.substring(3); 
+0

does not work,because of character 1 in location will be gone。 – PyThon

+0

@PyThon修好了,謝謝。 – Guy

0
String str = "hello world"; 
    char[] charArray = str.toCharArray(); 
    charArray[2] = Character.toUpperCase(charArray[2]); 
    str = new String(charArray); 
    System.out.println(str); 
0

此代碼的工作太

 String str = "hello world"; 
    str = str.replaceFirst(String.valueOf(str.charAt(2)), 
      String.valueOf(Character.toUpperCase(str.charAt(2)))); 
    System.out.println(str);