EN
Java - replace first 3 characters in string
3 points
In this article, we would like to show you how to replace the first 3 characters in string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xyz";
3
String result = replacement + text.substring(3);
4
5
System.out.println(result); // xyzD
or:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xyz";
3
String result = replacement.concat(text.substring(3));
4
5
System.out.println(result); // xyzD
or:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xyz";
3
String result = text.replaceAll("^.{3}", replacement);
4
5
System.out.println(result); // xyzD
In this example, we remove last 3 characters from the original string and add the replacement at the beginning.
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 + text.substring(3);
7
8
System.out.println(result); // xyzD
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); // xyzD
9
}
10
}
In this example, we use string replaceAll()
with "^.{3}"
regex to replace the first 3 characters in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks,{3}
- 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 = "xyz";
6
String result = text.replaceAll("^.{3}", replacement);
7
8
System.out.println(result); // xyzD
9
}
10
}
Note:
Regular expressions are slower than
substring()
method.