EN
Java - remove last 2 characters from string
1
points
1. Overview
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:
String original = "1234";
String expected = "12";
2. Remove char with String.substring()
Code example:
public class RemoveCharsExample1 {
public static void main(String[] args) {
String original = "1234";
String result = original.substring(0, original.length() - 2);
System.out.println(original); // 1234
System.out.println(result); // 12
}
}
Output:
1234
12
3. Remove char with StringBuilder.delete()
Code example:
public class RemoveCharsExample2 {
public static void main(String[] args) {
String original = "1234";
StringBuilder builder = new StringBuilder(original);
builder.delete(builder.length() - 2, builder.length());
String result = builder.toString();
System.out.println(original); // 1234
System.out.println(result); // 12
}
}
Output:
1234
12
4. Remove char with Java 8 Optional
Code example:
import java.util.Optional;
public class RemoveCharsExample3 {
public static void main(String[] args) {
String original = "1234";
String result = Optional.ofNullable(original)
.map(str -> str.substring(0, str.length() - 2))
.orElse(original);
System.out.println(original); // 1234
System.out.println(result); // 12
}
}
Output:
1234
12
5. Remove char with Apache Commons - StringUtils.substring()
Code example:
import org.apache.commons.lang3.StringUtils;
public class RemoveCharsExample4 {
public static void main(String[] args) {
String original = "1234";
String result = StringUtils.substring(original, 0, original.length() - 2);
System.out.println(original); // 1234
System.out.println(result); // 12
}
}
Output:
1234
12