EN
Java - replace last 3 characters in string
0 points
In this article, we would like to show you how to replace last 3 characters in string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "123";
3
String result = text.substring(0, text.length() - 3) + replacement;
4
5
System.out.println(result); // A123
In this example, we use substring()
method to remove last 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
String replacement = "123";
6
String result = text.substring(0, text.length() - 3) + replacement;
7
8
System.out.println("Original string: " + text); // ABCD
9
System.out.println("Modified string: " + result); // A123
10
}
11
}
Output:
xxxxxxxxxx
1
Original string: ABCD
2
Modified string: A123
Note:
The
replacement
length doesn't have to be equal to 3. You can remove the last 3 characters from the end of the string and add any number of characters instead.