How do I replace a character in a string in Java?
To replace a character in a string in Java, you can use the String.replace(char oldChar, char newChar)
method. This method returns a new string resulting from replacing all occurrences of oldChar
in this string with newChar
.
Here is an example of how you can use this method:
String str = "Hello World!";
str = str.replace('o', 'a');
System.out.println(str); // prints "Hell a Wrad!"
Alternatively, you can use the String.replace(CharSequence target, CharSequence replacement)
method, which replaces all occurrences of the specified sequence of characters with the specified replacement string.
Here is an example of how you can use this method:
String str = "Hello World!";
str = str.replace("o", "a");
System.out.println(str); // prints "Hell a Wrad!"