EN
Java - remove last character from string
14 points
In this post we will see how to remove last character from String in java.
All below examples except StringUtils.chop can be used to remove any number of characters from the end of the string.
Example:
xxxxxxxxxx
1
String original = "123";
2
String expected = "12";
Code example:
xxxxxxxxxx
1
public class RemoveCharExample1 {
2
3
public static void main(String[] args) {
4
String original = "123";
5
String result = original.substring(0, original.length() - 1);
6
7
System.out.println(original); // 123
8
System.out.println(result); // 12
9
}
10
}
Output:
xxxxxxxxxx
1
123
2
12
Code example:
xxxxxxxxxx
1
public class RemoveCharExample2 {
2
3
public static void main(String[] args) {
4
String original = "123";
5
6
StringBuilder builder = new StringBuilder(original);
7
builder.delete(builder.length() - 1, builder.length());
8
9
String result = builder.toString();
10
11
System.out.println(original); // 123
12
System.out.println(result); // 12
13
}
14
}
Output:
xxxxxxxxxx
1
123
2
12
Code example:
xxxxxxxxxx
1
import java.util.Optional;
2
3
public class RemoveCharExample3 {
4
5
public static void main(String[] args) {
6
String original = "123";
7
8
String result = Optional.ofNullable(original)
9
.map(str -> str.substring(0, str.length() - 1))
10
.orElse(original);
11
12
System.out.println(original); // 123
13
System.out.println(result); // 12
14
}
15
}
Output:
xxxxxxxxxx
1
123
2
12
Code example:
xxxxxxxxxx
1
import org.apache.commons.lang3.StringUtils;
2
3
public class RemoveCharExample4 {
4
5
public static void main(String[] args) {
6
String original = "123";
7
String result = StringUtils.chop(original);
8
9
System.out.println(original); // 123
10
System.out.println(result); // 12
11
}
12
}
Output:
xxxxxxxxxx
1
123
2
12
Code example:
xxxxxxxxxx
1
import org.apache.commons.lang3.StringUtils;
2
3
public class RemoveCharExample5 {
4
5
public static void main(String[] args) {
6
String original = "123";
7
String result = StringUtils.substring(original, 0, original.length() - 1);
8
9
System.out.println(original); // 1234
10
System.out.println(result); // 12
11
}
12
}
Output:
xxxxxxxxxx
1
123
2
12