java.lang.String class comes with replace() String method to replace existing characters in a sting with new characters.
The signature of replace() String as given in Java API.
- public String replace(char oldChar, char newChar): Returns a new string after replacing characters. All the occurrences of oldChar in the string are replaced by newChar.
In the following example, each occurrence of A in str1 is replaced by K and a new string is returned. Original string str1 is not disturbed.
public class StringMethodDemo
public static void main(String args)
String str1 = "ABCAEFGAIJK";
String str2 = str1.replace('A', 'K');
System.out.println("Original string before replacement: " + str1);
System.out.println("New string after replacing each A with K: " + str2);
Output screen on replace() String Example
Also refer for a similar method replaceFirst().
Pass your comments and suggestions on this tutorial "replace() String Example".