EN
Java - remove first 2 characters from string
0 points
In this article, we would like to show you how to remove the first 2 characters from the string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
3
String result = text.substring(2);
4
5
System.out.println(result); // CD
In this example, we use String substring()
method to create a new result
substring from the text
string without the first 2 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
6
String result = text.substring(2);
7
8
System.out.println(result); // CD
9
}
10
}
Output:
xxxxxxxxxx
1
CD
In this example, we create sb
StringBuilder object from the text
string, then we use delete()
method on the sb
to delete the first 2 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
6
// Create StringBuilder object
7
StringBuilder sb = new StringBuilder(text);
8
9
// Remove first 2 characters
10
sb.delete(0, 2);
11
12
System.out.println(sb);
13
}
14
}
Output:
xxxxxxxxxx
1
CD
In this example, we create sb
StringBuffer object from the text
string, then we use delete()
method on the sb
to delete the first 2 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
6
// Create StringBuffer object
7
StringBuffer sb = new StringBuffer(text);
8
9
// Remove first 2 characters
10
sb.delete(0, 2);
11
12
System.out.println(sb);
13
}
14
}
Output:
xxxxxxxxxx
1
CD