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