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:
String text = "ABCD";
int n = 3;
String result = text.substring(n);
System.out.println(result); // D
Â
Practical examples
1. Using String substring()
 method
In this example, we use String substring()
 method to create a new result
substring from the text
string without the first n
 characters.
Syntax:
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:
public class Example {
public static void main(String[] args) {
String text = "ABCD";
int n = 3;
String result = text.substring(n);
System.out.println(result); // D
}
}
Output:
D
2. Using StringBuilder delete()
method
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:
delete(int startIndex, int endIndex);
Practical example:
public class Example {
public static void main(String[] args) {
String text = "ABCD";
int n = 3;
// Create StringBuilder object
StringBuilder sb = new StringBuilder(text);
// Remove first n characters
sb.delete(0, n);
System.out.println(sb); // D
}
}
Output:
D
3. Using StringBuffer delete()
methodÂ
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:
delete(int startIndex, int endIndex);
Practical example:
public class Example {
public static void main(String[] args) {
String text = "ABCD";
int n = 3;
// Create StringBuffer object
StringBuffer sb = new StringBuffer(text);
// Remove first n characters
sb.delete(0, n);
System.out.println(sb);
}
}
Output:
D