Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

Remove Last Character from a String in Java

Learn to remove the last character from a String, either using the indices or only matching criteria. Learn to handle null and empty values.

Lokesh Gupta

October 10, 2023

Java String class
Java String
Java String

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
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

String Examples

  • String Constant Pool
  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • Align Left, Right, Center
  • Immutable Strings
  • StringJoiner
  • Split a string
  • Escape HTML
  • Unescape HTML
  • Convert to title case
  • Find duplicate words
  • Left pad a string
  • Right pad a string
  • Reverse recursively
  • Leading whitespaces
  • Remove whitespaces
  • Reverse words
  • Find duplicate characters
  • Get first 4 characters
  • Get last 4 characters
  • (123) 456-6789 Pattern
  • Interview Questions

String Methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

Table of Contents

  • 1. Delete Last Character using StringBuffer.deleteCahrAt()
  • 2. Remove Last Character using String.substring()
  • 3. Replace Last Char with Empty String using Regex
  • 4. Remove Last Character using StringUtils.chop()
  • 5. Remove Last Character if Char Value Matches
  • 6. Conclusion
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Sending XML Request with REST-assured

Next

How to Marshal and Unmarshal XML with Jackson

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.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap