EN
Java - replace first 2 characters in string
0 points
In this article, we would like to show you how to replace the first 2 characters in string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xy";
3
String result = replacement + text.substring(2);
4
5
System.out.println(result); // xyCD
or:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xy";
3
String result = replacement.concat(text.substring(2));
4
5
System.out.println(result); // xyCD
or:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xy";
3
String result = text.replaceAll("^.{2}", replacement);
4
5
System.out.println(result); // xyCD
In this example, we will take the last 2
characters from the original string and add them to the end of the replacement.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
String replacement = "xy";
6
String result = replacement + text.substring(2);
7
8
System.out.println(result); // xyCD
9
}
10
}
This approach is equivalent to the above one. Instead of +
operator we concatenate the strings using concat()
method.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
String replacement = "xyz";
6
String result = replacement.concat(text.substring(3));
7
8
System.out.println(result); // xyCD
9
}
10
}
In this example, we use string replaceAll()
with "^.{2}"
regex to replace the first 2 characters in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks,{2}
- matches the specified quantity of the previous token (in our case the.
).
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
String replacement = "xy";
6
String result = text.replaceAll("^.{2}", replacement);
7
8
System.out.println(result); // xyCD
9
}
10
}
Note:
Regular expressions are slower than
substring()
method.