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