EN
Java - replace part of string from given index
0 points
In this article, we would like to show you how to replace part of string from given index in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
String replacement = "xy";
3
4
int position = 1; // replace CD at index 1
5
int numberOfCharacters = 2; // number of characters to replace
6
7
String result = text.substring(0, position) + replacement + text.substring(position + numberOfCharacters);
8
9
System.out.println(text); // ABCD
10
System.out.println(result); // AxyD
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
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
String replacement = "xy";
6
7
int position = 1; // we want to replace CD
8
int numberOfCharacters = 2; // number of characters we want to replace
9
10
String result = text.substring(0, position) + replacement + text.substring(position + numberOfCharacters);
11
12
System.out.println("Original string: " + text); // ABCD
13
System.out.println("Modified string: " + result); // AxyD
14
}
15
}
Output:
xxxxxxxxxx
1
Original string: ABCD
2
Modified string: AxyD