EN
Java - replace all occurrences of string
0
points
In this article, we would like to show you how to replace all occurrences of string in Java.
Quick solution:
String text = "ABC ABC ABC";
String replacement = "X";
String result = text.replaceAll("C", replacement);
System.out.println(result); // ABX ABX ABX
1. Practical example using String replaceAll()
method
In this example, we use replaceAll()
method to replace all occurrences of the "C
" in the text
string to "X
".
public class Example {
public static void main(String[] args) {
String text = "ABC ABC ABC";
String replacement = "X";
String result = text.replaceAll("C", replacement);
System.out.println("Original text: " + text); // ABC ABC ABC
System.out.println("Modified text: " + result); // ABX ABX ABX
}
}
Output:
Original text: ABC ABC ABC
Modified text: ABX ABX ABX
2. Practical example using String replace()
method
In this example, we use replace()
method to replace all occurrences of the "C
" in the text
string to "X
".
public class Example {
public static void main(String[] args) {
String text = "ABC ABC ABC";
String replacement = "X";
String result = text.replace("C", replacement);
System.out.println("Original text: " + text); // ABC ABC ABC
System.out.println("Modified text: " + result); // ABX ABX ABX
}
}
Output:
Original text: ABC ABC ABC
Modified text: ABX ABX ABX
Note:
The difference between
replace()
andreplaceAll()
is insignificant. ThereplaceAll()
method takes regex as the first argument, whilereplace()
takes char or CharSequence.