EN
Java - remove last 2 characters from string
1 points
In this post, we will see how to remove the last 2 characters from any String in java.
In the below examples, we can change the number of characters we want to remove.
We can remove the last n characters. For example, we can remove the last character, last 3, 4, 5 x characters. We just need to ensure that the string is long enough.
Example:
xxxxxxxxxx
1
String original = "1234";
2
String expected = "12";
Code example:
xxxxxxxxxx
1
public class RemoveCharsExample1 {
2
3
public static void main(String[] args) {
4
String original = "1234";
5
String result = original.substring(0, original.length() - 2);
6
7
System.out.println(original); // 1234
8
System.out.println(result); // 12
9
}
10
}
Output:
xxxxxxxxxx
1
1234
2
12
Code example:
xxxxxxxxxx
1
public class RemoveCharsExample2 {
2
3
public static void main(String[] args) {
4
String original = "1234";
5
6
StringBuilder builder = new StringBuilder(original);
7
builder.delete(builder.length() - 2, builder.length());
8
9
String result = builder.toString();
10
11
System.out.println(original); // 1234
12
System.out.println(result); // 12
13
}
14
}
Output:
xxxxxxxxxx
1
1234
2
12
Code example:
xxxxxxxxxx
1
import java.util.Optional;
2
3
public class RemoveCharsExample3 {
4
5
public static void main(String[] args) {
6
String original = "1234";
7
8
String result = Optional.ofNullable(original)
9
.map(str -> str.substring(0, str.length() - 2))
10
.orElse(original);
11
12
System.out.println(original); // 1234
13
System.out.println(result); // 12
14
}
15
}
Output:
xxxxxxxxxx
1
1234
2
12
Code example:
xxxxxxxxxx
1
import org.apache.commons.lang3.StringUtils;
2
3
public class RemoveCharsExample4 {
4
5
public static void main(String[] args) {
6
String original = "1234";
7
String result = StringUtils.substring(original, 0, original.length() - 2);
8
9
System.out.println(original); // 1234
10
System.out.println(result); // 12
11
}
12
}
Output:
xxxxxxxxxx
1
1234
2
12