Remove last character from end of a String in Java
This post will discuss how to remove the last character from the end of a String in Java.
1. Using String.substring() method
To chop the last character from the string’s end, you can simply make a call to the substring() method with the last index excluded. Here’s a utility method demonstrating this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static String removeLastChar(String str) { if (str == null || str.length() == 0) { return str; } return str.substring(0, str.length() - 1); } public static void main(String[] args) { String str = "Java8"; System.out.println(removeLastChar((str))); // Java } } |
2. Using String.replaceFirst() method
Both replaceFirst() and replaceAll() method accepts regular expression for substring replacement. You can use the regular expression .$ to match with the last character of a string. Here, . matches with any character except a line terminator, and $ matches with the end of a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static String removeLastChar(String str) { if (str == null) { return null; } return str.replaceFirst(".$", ""); } public static void main(String[] args) { String str = "Java8"; System.out.println(removeLastChar((str))); // Java } } |
3. Using StringUtils.chop() method
This post is incomplete without a solution that doesn’t re-invent the wheels. Apache Commons StringUtils class has a chop() method that removes the last part of a String.
|
1 2 3 4 5 6 7 8 9 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String str = "Java8"; System.out.println(StringUtils.chop(str)); // Java } } |
If you have a specific substring to be removed from the end of a string, you may use the removeEnd() method from the StringUtils class.
|
1 2 3 4 5 6 7 8 9 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String str = "Java8"; System.out.println(StringUtils.removeEnd(str, "8")); // Java } } |
That’s all about removing the last character from the end of a String in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)