In this post, we will see how to remove last character from String in java.
There are many ways to do it. Let’s see each one by one.
Table of Contents
Using String.substring()
We can use inbuilt String’s substring() method to remove last character.We need two parameters here
start index: 0
end index:str.length()-1
1 2 3 |
str.substring(0, str.length() - 1); |
Please note that this method is not thread safe and it will fail with empty or null String.
So here is java program to remove last character from String in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class RemoveLastCharStringMain { public static void main(String[] args) { RemoveLastCharStringMain rlc=new RemoveLastCharStringMain(); String str="java2blog"; str=rlc.removeLastChar(str); System.out.println(str); } private String removeLastChar(String str) { return str.substring(0, str.length() - 1); } } |
Output:
Using StringUtils.chop()
You need to add below dependency to get Apache commons lang jar.
1 2 3 4 5 6 7 |
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> |
and then use StringUtils.chop() method to remove last character from the String in java,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; import org.apache.commons.lang3.StringUtils; public class RemoveLastCharStringMain { public static void main(String[] args) { String str="java2blog"; str=StringUtils.chop(str); System.out.println(str); } } |
Output:
Using Regular Expression
We can make use of Regular expression also to remove last character from String in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class RemoveLastCharStringMain { public static void main(String[] args) { RemoveLastCharStringMain rlc=new RemoveLastCharStringMain(); String str="java2blog"; str=rlc.removeLastChar(str); System.out.println(str); } public String removeLastChar(String s) { return (s == null) ? null : s.replaceAll(".$", ""); } } |
Output:
Using StringBuffer/StringBuilder
We can StringBuffer's
deleteCharAt()
to remove last character from String in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; public class RemoveLastCharStringMain { public static void main(String[] args) { RemoveLastCharStringMain rlc = new RemoveLastCharStringMain(); String str = "java2blog"; str = rlc.removeLastChar(str); System.out.println(str); } private String removeLastChar(String str) { StringBuilder sb = new StringBuilder(str); sb.deleteCharAt(sb.length() - 1); return sb.toString(); } } |
Output:
That’s all about how to remove last character from String in java.