C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This replace call changes all characters with matching values, not just the first one. This is important to remember.
Java program that uses replace, char
public class Program {
public static void main(String[] args) {
String value = "Java";
// Replace letter with underscore.
String result = value.replace('a', '_');
System.out.println(result);
}
}
Output
J_v_
Tip: This version of replace checks the entire string for all possible replacements. It does not just replace the first one.
Java program that uses replace, CharSequence
public class Program {
public static void main(String[] args) {
String animals = "cat cat dog";
// Replace all CharSequences (strings) with another.
String result = animals.replace("cat", "mouse");
System.out.println(result);
}
}
Output
mouse mouse dog
Java program that uses replaceFirst
public class Program {
public static void main(String[] args) {
String pets = "cat cat dog";
// Replace first instance of "cat".
String result = pets.replaceFirst("cat", "bird");
System.out.println(result);
}
}
Output
bird cat dog
So: The substrings a100z, a200z and a300z are matched and replaced. But the substring b100z is not.
Java program that uses replaceAll
public class Program {
public static void main(String[] args) {
String codes = "a100z a200z a300z b100z";
// Replace all matches with a string.
String result = codes.replaceAll("a\\d\\d\\dz", "a---z");
System.out.println(result);
}
}
Output
a---z a---z a---z b100z
Here: The string contains three "cats." We only replace the final, ending cat with a "dog" string.
Java program that replaces end string
public class Program {
public static void main(String[] args) {
String pets = "cat cat cat";
// Use metacharacter to ensure the replacement is at the end.
String result = pets.replaceFirst("cat$", "dog");
System.out.println(result);
}
}
Output
cat cat dog
Here: The first string contains HTML, so we call replace() on it. But the second string does not, so we skip it.
Tip: This optimization depends on the data being processed in a program, and the exact logic. But it is sometimes worth doing.
Java program that avoids replace calls
public class Program {
public static String replaceIfNeeded(String value) {
// Test the string to see if any of the replacements can succeed.
if (value.contains("<span>")) {
value = value.replace("<span><b>", "*");
value = value.replace("<span><i>", "/");
}
if (value.contains("</span>")) {
value = value.replace("</b></span>", "*");
value = value.replace("</i></span>", "/");
}
return value;
}
public static void main(String[] args) {
// ... All replace calls are used on this string.
String result = replaceIfNeeded("<span><b>Cat</b></span>");
System.out.println(result);
// ... No replace calls are needed.
result = replaceIfNeeded("Dog");
System.out.println(result);
}
}
Output
*Cat*
Dog