Explain Codes LogoExplain Codes Logo

How to remove the last character from a string?

java
string-manipulation
substring
regex
Alex KataevbyAlex Kataev·Feb 20, 2025
TLDR

Quickly remove the last character of a Java string with this code snippet:

String str = "Java!"; str = str.substring(0, str.length() - 1); // The '!' is gone: "Java"

Take note: always check if the string is non-empty using str.isEmpty() to avoid StringIndexOutOfBoundsException.

Handling strings with care

When trimming the tail of strings, it's vital to be cautious. To safely remove the last character of a string, the substring() method is quite handy and relatively safe. However, you must consider null strings and edge cases involving empty strings or strings with a single character.

Checking before acting

To avoid runtime exceptions, always check the length of the string:

if (str != null && !str.isEmpty()) { str = str.substring(0, str.length() - 1); // Goodbye last char, nobody liked you anyway! }

If condition met, off with its tail!

You may want to get rid of the last character only if it matches a certain condition. For instance, chopping off a pesky trailing comma:

if (str != null && str.endsWith(",")) { str = str.substring(0, str.length() - 1); // Sayonara, comma! }

Regex: Cut it off, with style!

Your knight in shining armor for flexible removal is regular expression (Regex):

str = str.replaceFirst(".$", ""); // Here today, gone tomorrow!

Heads up! Regex and special characters don't have the best relationship, so handle those special characters with care!

A masterclass in string operations

For those who want to delve deeper, you can unleash the power of regex and StringUtils from the versatile Apache Commons.

Regex: When the scissors don't fit the paper

You can use regex to surgically remove the last character if it matches your specific pattern:

str = str.replaceFirst("[aeiou]$", ""); // Goodbye last vowel. Consonants party!

Apache Commons: More than meet the eyes

Let StringUtils from Apache Commons be your assistant for advanced removal:

String str = StringUtils.removeEnd(str, String.valueOf(str.charAt(str.length() - 1))); // StringUtils to the rescue!

Fast and furious

For those burning rubber, check out these hot alternatives:

  • StringBuilder: Build and manipulate strings like Lego bricks:

    StringBuilder sb = new StringBuilder(str); sb.deleteCharAt(sb.length() - 1); str = sb.toString(); //Feels like plastic surgery!
  • Char array: Go to the nitty-gritty with low-level operations:

    char[] chars = str.toCharArray(); str = new String(chars, 0, chars.length - 1); //Feels like slow-motion dissection!
  • Functional style: Show off your Lambdas:

    str = Stream.of(str.split("")) .limit(str.length() - 1) .collect(Collectors.joining()); //Feels like streamline magic!

Apply each technique wisely for maximum brownie points!

Concise can also be safe

For those who dream in code, here's a way to remove the last character with a single line of code. It still checks if the string is non-null and has a length before proceeding:

str = (str != null && str.length() > 0) ? str.substring(0, str.length() - 1) : str; //The magical line!

Hardening the shield

A good knight knows how to defend. Consider all edge cases and unexpected inputs:

  • What if the string is null?
  • What if it's empty or one-character-long?
  • What if the last character is a space you want to keep?

Write code that's ready for anything!