Languages
[Edit]
EN

Java - replace first n characters in string

3 points
Created by:
Tehya-Blanchard
324

In this article, we would like to show you how to replace the first n characters in String in Java.

Quick solution:

int n = 3;
String text = "ABCD";
String replacement = "xyz";
String result = replacement + text.substring(n);

System.out.println(result);  // xyzD

or:

int n = 3;
String text = "ABCD";
String replacement = "xyz";
String result = replacement.concat(text.substring(n));

System.out.println(result);  // xyzD

 

Practical example using String substring()

1.1 With + operator

In this example, we remove last n characters from the original string and add the replacement at the beginning.

public class Example {

    public static void main(String[] args) {

        int n = 3;
        String text = "ABCD";
        String replacement = "xyz";
        String result = replacement + text.substring(n);

        System.out.println(result);  // xyzD
    }
}

1.2 With concat() method

This approach is equivalent to the above one. Instead of + operator, we concatenate the strings using concat() method.

public class Example {

    public static void main(String[] args) {

        int n = 3;
        String text = "ABCD";
        String replacement = "xyz";
        String result = replacement.concat(text.substring(n));

        System.out.println(result);  // xyzD
    }
}

Java - String (popular problems)

Java - replace first n 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