Java’s replaceString function is very handy for string and substring modifications.
public class ReplaceString {
public static void main(String[] args) {
// replacing a character in string
String str = "replacestring";
System.out.println(str.replace("a","e"));
// removing a character from string
System.out.println(str.replace("a", ""));
// replacing a substring in a string
System.out.println(str.replace("replace", "remove"));
// removing a substring in a string
System.out.println(str.replace("replace", ""));
// replacing a symbol from a string
str = "$40.36";
str = str.replace("$", "CAD ");
System.out.println(str);
}
}
output
replecestring
replcestring
removestring
string
CAD 40.36
- First part of the all occurrences of a with e
- Second part remove all occurrences of the character a
- Third part replaces the substring replace with the substring remove
- Fourth part removes ths substring replace
- Last part shows that special symbols can also be replaced. They don’t need to be escaped with backslash