Languages
[Edit]
EN

Java - replace part of string from given index

0 points
Created by:
Lia-Perez
355

In this article, we would like to show you how to replace part of string from given index in Java.

Quick solution:

String text = "ABCD";
String replacement = "xy";

int position = 1;            // replace CD at index 1
int numberOfCharacters = 2;  // number of characters to replace

String result = text.substring(0, position) + replacement + text.substring(position + numberOfCharacters);

System.out.println(text);     // ABCD
System.out.println(result);   // AxyD

 

Practical example using substring() method

In this example, we replace part of the text string - CD at index 1 that is 2 characters long. To do so we use substring() method and + operator to add strings and receive the result.

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";
        String replacement = "xy";

        int position = 1;            // we want to replace CD
        int numberOfCharacters = 2;  // number of characters we want to replace

        String result = text.substring(0, position) + replacement + text.substring(position + numberOfCharacters);

        System.out.println("Original string: " + text);     // ABCD
        System.out.println("Modified string: " + result);   // AxyD
    }
}

Output:

Original string: ABCD
Modified string: AxyD

Java - String (popular problems)

Java - replace part of string from given index
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