EN
Java - remove substring from string between indexes
0 points
In this article, we would like to show you how to create your own function to remove substring from a string in Java.
xxxxxxxxxx
1
public class StringExample {
2
3
static String removeSubstring(String text, int startIndex, int endIndex) {
4
if (endIndex < startIndex) {
5
startIndex = endIndex;
6
}
7
8
String a = text.substring(0, startIndex);
9
String b = text.substring(endIndex);
10
11
return a + b;
12
}
13
14
public static void main(String[] args) {
15
// Usage example:
16
17
// index: 0 5 7 11 14
18
// | | | | |
19
String text = "This is my text";
20
21
System.out.println( removeSubstring(text, 0, 5)); // is my text
22
System.out.println( removeSubstring(text, 5, 7)); // This my text
23
System.out.println( removeSubstring(text, 1, text.length() - 1)); // Tt
24
}
25
}
Output:
xxxxxxxxxx
1
is my text
2
This my text
3
Tt