EN
Java - remove first n characters from string
0 points
In this article, we would like to show you how to remove the first n characters from the string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
int n = 3;
3
String result = text.substring(n);
4
5
System.out.println(result); // D
In this example, we use String substring()
method to create a new result
substring from the text
string without the first n
characters.
Syntax:
xxxxxxxxxx
1
substring(int startIndex, int endIndex);
Note:
By default
endIndex
is the end of the string, so we don't need to specify it.
Practical example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
int n = 3;
6
String result = text.substring(n);
7
8
System.out.println(result); // D
9
}
10
}
Output:
xxxxxxxxxx
1
D
In this example, we create sb
StringBuilder object from the text
string, then we use delete()
method on the sb
to delete the first n
characters.
Syntax:
xxxxxxxxxx
1
delete(int startIndex, int endIndex);
Practical example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
int n = 3;
6
7
// Create StringBuilder object
8
StringBuilder sb = new StringBuilder(text);
9
10
// Remove first n characters
11
sb.delete(0, n);
12
13
System.out.println(sb); // D
14
}
15
}
Output:
xxxxxxxxxx
1
D
In this example, we create sb
StringBuffer object from the text
string, then we use delete()
method on the sb
to delete the first n
characters.
Syntax:
xxxxxxxxxx
1
delete(int startIndex, int endIndex);
Practical example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
int n = 3;
6
7
// Create StringBuffer object
8
StringBuffer sb = new StringBuffer(text);
9
10
// Remove first n characters
11
sb.delete(0, n);
12
13
System.out.println(sb);
14
}
15
}
Output:
xxxxxxxxxx
1
D