EN
Java - replace first n characters in string
3 points
In this article, we would like to show you how to replace the first n characters in String in Java.
Quick solution:
xxxxxxxxxx
1
int n = 3;
2
String text = "ABCD";
3
String replacement = "xyz";
4
String result = replacement + text.substring(n);
5
6
System.out.println(result); // xyzD
or:
xxxxxxxxxx
1
int n = 3;
2
String text = "ABCD";
3
String replacement = "xyz";
4
String result = replacement.concat(text.substring(n));
5
6
System.out.println(result); // xyzD
In this example, we remove last n
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
5
int n = 3;
6
String text = "ABCD";
7
String replacement = "xyz";
8
String result = replacement + text.substring(n);
9
10
System.out.println(result); // xyzD
11
}
12
}
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
5
int n = 3;
6
String text = "ABCD";
7
String replacement = "xyz";
8
String result = replacement.concat(text.substring(n));
9
10
System.out.println(result); // xyzD
11
}
12
}