EN
Java - replace last 4 characters in string
14
points
Problem:
I have:
String str = "123456";
I want:
String str = "12abcd";
Solution:
We can replace / change last 4 x characters in any string in java with String.substring
String str = "123456";
System.out.println(str.substring(0, str.length() - 4) + "abcd"); // 12abcd
1. use substring
2. and add missing 4 x letters
Note:
Logic works for N x chars
Ensure that the length of string is longer than N
Docs:
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-