How to Remove Last Character from String in Java?

In Java, there are mainly three classes related to the String. The classes are String, StringBuilder, and StringBuffer class. These three classes provide methods related to string manipulation. Removing the first and last character from the String is also an operation that we can perform on the string.

In this section, we will learn how to remove the last character from String in Java. At the last of this section, we have also explained how to delete the first and last character of each word in a string.

There are five ways to remove the last character from a string:

  • Using StringBuffer.deleteCahrAt() Class
  • Using String.substring() Method
  • Using StringUtils.chop() Method
  • Using Regular Expression
  • Using StringBuilder

Using StringBuffer Class

The StringBuffer class provides a method deleteCharAt(). The method deletes a character from the specified position. We use the method to remove a character from a string in Java. It accepts a parameter index of type int. The index is the position of a character we want to delete. It returns this object.

Syntax:

It throws StringIndexOutOfBoundsException if we specify a negative index or the index is greater than or equal to the length of the string.

Let's implement the method in an example.

RemoveLastCharcter1.java

Output:

Javatpoint is the best educational website

In the above output, we see that the last character s has been deleted.

Pros:

  • Simple and straightforward.
  • Directly removes the last character from the StringBuffer object.

Cons:

  • Requires conversion to and from StringBuffer that may result in additional overhead.
  • StringBuffer is synchronized and thus slower than StringBuilder.

Using String.substring() Method

The substring() is the method of the String class. It parses two parameters beginIndex and endIndex of type int. It returns a new string (sub-string). It is not thread-safe because does not throws an exception if the string is null or empty.

Syntax:

If the beginIndex is negative or beginIndex > endIndex or the endIndex > length of the string it throws IndexOutOfBoundsException.

RemoveLastCharacter2.java

Output:

Welcome to Javatpoin

Pros:

  • Simple and concise code.
  • Utilizes existing String methods without the need for additional classes.

Cons:

  • Creates a new string object that may impact memory usage for large strings.
  • Not as efficient as directly modifying the string.

Using StringUtils.chop() Method

The StringUtils class provides a chop() method to remove the last character from a string. The method parses a parameter of type String. It also accepts null, as a parameter. It returns the string after removing the last character. It also returns a null string when we input a null string.

Syntax:

For using the chop() method of the StringUtils class, we need to add the following dependency in the pom.xml file. When we add the Apache commons lang3 jar in the pom file it downloads the jar file and add the jar file to the path. We must import the package org.apache.commons.lang3.StringUtils

After adding the dependency, we can call the chop() method of StringUtils class to remove the last character from the string.

RemoveLastCharacter3.java

Output:

Googl

Pros:

  • Provides a convenient method specifically for removing the last character.
  • Handles null strings gracefully.

Cons:

  • Requires the inclusion of Apache Commons Lang library, which increases project dependencies.
  • Dependency may not be desirable for projects with strict dependency requirements.

Using Regular Expression

We can also use the regular expression to remove or delete the last character from the string. The String class provides the replaceAll() method that parses two parameters regex and replacement of type String. The method replaces the string with the specified match.

  • regex: It is the expression with which the string is to match.
  • replacement: It is the replacement string or substitute string for each match.

It returns the resulting substring.

Syntax:

It throws PatternSyntaxException if the regular expression syntax is invalid.

RemoveLastCharacter4.java

Output:

Honesty is the best polic

Pros:

  • Offers flexibility in pattern matching.
  • Can handle more complex removal patterns.

Cons:

  • Regular expression processing can be slower compared to direct string manipulation.
  • Overhead of regex pattern parsing.

Using StringBuilder Class

Another approach to remove the last character from a string is by using the StringBuilder class. StringBuilder provides a convenient deleteCharAt() method that allows us to remove a character at a specified index.

Here's how we can utilize StringBuilder to remove the last character:

In this example, sb.deleteCharAt(originalString.length() - 1) removes the last character from the StringBuilder object, and then toString() method converts the StringBuilder back to a string.

Here's a complete Java code example demonstrating how to remove the last character from a string using the StringBuilder class:

RemoveLastCharacterExample.java

Output:

Original String: Hello World
Modified String: Hello Worl

Pros:

  • Offers direct manipulation of the string without creating additional objects.
  • Utilizes StringBuilder's efficient methods.

Cons:

  • Requires conversion to and from StringBuilder that may incur overhead.
  • StringBuilder is not synchronized, so it is not thread-safe.

Removing the First and Last Character of Each Word in a String

We can also remove or delete the first and last character of each word in a string. To remove the first and last character, we use the following steps:

  • Split (break) the String based on the space.
  • For each word, run a loop form the first to last letter.
  • Identify the first and last character of each word.
  • Now, delete the first and last character of each word.

RemoveFirstAndLastCharacter.java

Output:

Javatpoint is the best educational website
avatpoin  h es ducationa ebsit

In the above output, we see that the first and last character has been removed from each word of the string. The word "is" has been removed completely because it has only two characters.

Comparison Summary

  • Complexity: All methods are relatively simple to implement, but some require additional classes or dependencies.
  • Performance: Direct manipulation methods like StringBuilder or StringBuffer.deleteCharAt() are generally more efficient than creating new string objects (String.substring() or String.replaceAll()).
  • Dependencies:chop() requires Apache Commons Lang library, which may not be suitable for all projects.
  • Readability:substring() and StringBuilder.deleteCharAt() are straightforward and commonly understood methods, while regular expressions may be more cryptic for those unfamiliar with them.
  • Flexibility: Regular expressions offer the most flexibility for complex pattern matching, while other methods are more limited in functionality.

Conclusion

In conclusion, Java offers several methods for removing the last character from a string, each with its own trade-offs. StringBuffer.deleteCharAt() and StringBuilder.deleteCharAt() provide direct manipulation options, while String.substring() offers simplicity at the cost of potentially increased memory usage. StringUtils.chop() provides convenience but adds external dependencies, while regular expressions offer flexibility but may introduce performance overhead. The choice of method depends on factors such as performance requirements, code readability, and project dependencies.