EN
Java - replace last n characters in string
0 points
In this article, we would like to show you how to replace last n characters in string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
int n = 3;
3
String replacement = "123";
4
String result = text.substring(0, text.length() - n) + replacement;
5
6
System.out.println(result); // A123
In this example, we use substring()
method to remove last n = 3
characters from the text
string, then we add the replacement
at their place.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
int n = 3;
6
String replacement = "123";
7
String result = text.substring(0, text.length() - n) + replacement;
8
9
System.out.println("Original string: " + text); // ABCD
10
System.out.println("Modified string: " + result); // A123
11
}
12
}
Output:
xxxxxxxxxx
1
Original string: ABCD
2
Modified string: A123
Note:
The
replacement
length doesn't have to be equal ton
. You can remove the lastn
characters from the end of the string and add any number of characters instead.