Remove Last Character from a String in Java

Learn how to remove the last character from a String in Java using simple-to-follow examples. Also, learn how they handle null and empty strings while removing the last character from a string.

String str = "Hello, World!";

//Using Regex
String newStr = str.replaceAll(".$", "");   

//Using Substring Method
String newStr = str.substring(0, str.length() - 1);

//Using StringBuffer
StringBuffer stringBuffer = new StringBuffer(str);
String newStr = stringBuffer.deleteCharAt(stringBuffer.length() - 1);

//Using Apache Commons Lang - MOST READABLE
String newStr = StringUtils.chop(str);

1. Delete Last Character using StringBuffer.deleteCahrAt()

The deleteCharAt() method is a member of the StringBuffer class which deletes a character at a specified index.

public StringBuffer deleteCharAt(int index)

In the following example, we have a string “Hello, World!” and we are using the StringBuffer.deleteCharAt() method to delete the last character.

String str = "Hello, World!";
StringBuffer stringBuffer = new StringBuffer(str);

if (stringBuffer.length() > 0) {
    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
}

System.out.println(stringBuffer.toString()); // Output: Hello, World

2. Remove Last Character using String.substring()

This is the most straightforward technique. The substring() method returns a substring between begin and end indices.

Note that this method does not check for null string. It also does not check for the length of the String, so if we pass an empty string then we may get IndexOutOfBoundsException. It is better to write our own method of handling these two cases. Feel free to customize the method and handle more cases such as non-printable characters.

public static String removeLastChar(String s) {
  return (s == null || s.length() == 0)
      ? null
      : (s.substring(0, s.length() - 1));
}

Now we can use this method with any type of String.

newStr = removeLastChar(null);		//returns null
newStr = removeLastChar("");			//returns null
newStr = removeLastChar("a");			//returns "" empty string
newStr = removeLastChar("abcd");	       //returns "abc"

3. Replace Last Char with Empty String using Regex

The regular expression can be used to locate the last character of a String, and then we can replace it with the empty space, effectively deleting the last character from the output string.

String str = "Hello, World!";

String newStr = str.replaceAll(".$", "");

4. Remove Last Character using StringUtils.chop()

The StringUtils class is part of Apache Commons Lang library so add it if not already.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

The StringUtils.chop() returns a new string whose last character has been removed. This technique is noll-safe and handles empty strings as well.

Also, note that if the string ends in \r\n, then it removes both of them.

newStr = StringUtils.chop(null);		//returns null
newStr = StringUtils.chop("");			//returns "" empty string
newStr = StringUtils.chop("a");			//returns "" empty string
newStr = StringUtils.chop("abcd");	//returns "abc"

5. Remove Last Character if Char Value Matches

There may be usecases when we want to remove the last character only if it matches or does not match any specific character. We can achieve it using Guava’s CharMatcher class.

Include Guava to the project if not already.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

Use the CharMatcher class as follows to remove the string’s last character if it matches the given condition.

String string = "abcdE";
String newStr = CharMatcher.is('E').trimTrailingFrom(s);

We can use CharMatcher to remove breaking whitespaces as well.

String newStr = CharMatcher.breakingWhitespace().trimTrailingFrom(s);

6. Conclusion

In this short Java tutorial, we learned a few techniques to remove the last character from a String, either using the indices or only matching criteria. We saw how these methods handle null and empty values.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode