0

I am trying to replace only one character of a string. But whenever the character has multiple occurrences within the string, all of those characters are being replaced, while I only want the particular character to be replaced. For example:

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

Gives the result:

heLLo worLd

while I want it to be:

heLlo world

What can I do to achieve this?

Satrajit
  • 52
  • 8
  • 1
    See this Link for several methods on how to solve this: http://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string – slashNburn Mar 05 '16 at 16:46

5 Answers5

0

You should use a StringBuilder instead of String to achieve this goal.

Xvolks
  • 2,065
  • 1
  • 21
  • 32
0

replace will not work because it replace all the occurrence in the string. Also replaceFirst will not work as it will always remove the first occurrence.

As Strings are non mutable , so in either way you need create a new string always. Can be done by either of the following.

  • Use substring, and manually create the string that you want.

    int place = 2;
    str = str.substring(0,place)+Character.toUpperCase(str.charAt(place))+str.substring(place+1);
    
  • Convert the string to array of characters and replace any character that you want by using index, and then convert array back to the string.

PyThon
  • 1,007
  • 9
  • 22
0

replace(char, char) will replace all occurrences of the specified char, not only the char at the index. From the documentation

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

You can do something like

String str = "hello world";
String newStr = str.substring(0, 2) + Character.toUpperCase(str.charAt(2)) + str.substring(3);
Guy
  • 46,488
  • 10
  • 44
  • 88
0
    String str = "hello world";
    char[] charArray = str.toCharArray();
    charArray[2] = Character.toUpperCase(charArray[2]);
    str = new String(charArray);
    System.out.println(str);
PyThon
  • 1,007
  • 9
  • 22
Raphael Roth
  • 26,751
  • 15
  • 88
  • 145
0

This code works too

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