Languages
[Edit]
EN

Java - replace last 4 chars in any string

14 points
Created by:
AnnLen
9180

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 then N

Docs:
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join