Languages
[Edit]
EN

Java - replace last 4 chars in any string

14 points
Created by:
AnnLen
1777

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-

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.