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:
xxxxxxxxxx
1
String text = "ABC ABC ABC";
2
String replacement = "X";
3
String result = text.replaceAll("C", replacement);
4
5
System.out.println(result); // ABX ABX ABX
In this example, we use replaceAll()
method to replace all occurrences of the "C
" in the text
string to "X
".
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC ABC ABC";
5
String replacement = "X";
6
String result = text.replaceAll("C", replacement);
7
8
System.out.println("Original text: " + text); // ABC ABC ABC
9
System.out.println("Modified text: " + result); // ABX ABX ABX
10
}
11
}
Output:
xxxxxxxxxx
1
Original text: ABC ABC ABC
2
Modified text: ABX ABX ABX
In this example, we use replace()
method to replace all occurrences of the "C
" in the text
string to "X
".
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC ABC ABC";
5
String replacement = "X";
6
String result = text.replace("C", replacement);
7
8
System.out.println("Original text: " + text); // ABC ABC ABC
9
System.out.println("Modified text: " + result); // ABX ABX ABX
10
}
11
}
Output:
xxxxxxxxxx
1
Original text: ABC ABC ABC
2
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.