Languages
[Edit]
EN

Java - replace last 4 characters in string

14 points
Created by:
Kara
541

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-

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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