Languages
[Edit]
EN

Java - replace last 4 characters in string

14 points
Created by:
AnnLen
13540

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-

Java - String (popular problems)

Java - replace last 4 characters in string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join