How to remove the last character from a string?

JavaString

Java Problem Overview


I want to remove the last character from a string. I've tried doing this:

public String method(String str) {
    if (str.charAt(str.length()-1)=='x'){
        str = str.replace(str.substring(str.length()-1), "");
        return str;
    } else{
        return str;
    }
}

Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.

For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.

Java Solutions


Solution 1 - Java

replace will replace all instances of a letter. All you need to do is use substring():

public String method(String str) {
    if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
        str = str.substring(0, str.length() - 1);
    }
    return str;
}

Solution 2 - Java

Why not just one liner?

public static String removeLastChar(String str) {
    return removeLastChars(str, 1);
}

public static String removeLastChars(String str, int chars) {
    return str.substring(0, str.length() - chars);
}

Full Code

public class Main {
    public static void main (String[] args) throws java.lang.Exception {
        String s1 = "Remove Last CharacterY";
        String s2 = "Remove Last Character2";
        System.out.println("After removing s1==" + removeLastChar(s1) + "==");
        System.out.println("After removing s2==" + removeLastChar(s2) + "==");
    }
    
    public static String removeLastChar(String str) {
        return removeLastChars(str, 1);
    }

    public static String removeLastChars(String str, int chars) {
        return str.substring(0, str.length() - chars);
    }
}

Demo

Solution 3 - Java

Since we're on a subject, one can use regular expressions too

"aaabcd".replaceFirst(".$",""); //=> aaabc	

Solution 4 - Java

The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.

Example:

StringUtils.removeEnd("string 1|string 2|string 3|", "|");

Would result in: "string 1|string 2|string 3"

Solution 5 - Java

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

Solution 6 - Java

Don't try to reinvent the wheel, while others have already written libraries to perform string manipulation: org.apache.commons.lang3.StringUtils.chop()

Solution 7 - Java

In Kotlin you can used dropLast() method of the string class. It will drop the given number from string, return a new string

var string1 = "Some Text"
string1 = string1.dropLast(1)

Solution 8 - Java

Use this:

 if(string.endsWith("x")) {

	string= string.substring(0, string.length() - 1);
 }

Solution 9 - Java

if (str.endsWith("x")) {
  return str.substring(0, str.length() - 1);
}
return str;

> For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.

In case you're trying to stem English words

> Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form. > > ... > > A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".

https://stackoverflow.com/questions/5068790/difference-between-lucene-stemmers-englishstemmer-porterstemmer-lovinsstemmer outlines some Java options.

Solution 10 - Java

As far as the readability is concerned, I find this to be the most concise

StringUtils.substring("string", 0, -1);

The negative indexes can be used in Apache's StringUtils utility. All negative numbers are treated from offset from the end of the string.

Solution 11 - Java

 string = string.substring(0, (string.length() - 1));

I'm using this in my code, it's easy and simple. it only works while the String is > 0. I have it connected to a button and inside the following if statement

if (string.length() > 0) {
    string = string.substring(0, (string.length() - 1));
}

Solution 12 - Java

public String removeLastChar(String s) {
    if (!Util.isEmpty(s)) {
        s = s.substring(0, s.length()-1);
    }
    return s;
}

Solution 13 - Java

removes last occurence of the 'xxx':

    System.out.println("aaa xxx aaa xxx ".replaceAll("xxx([^xxx]*)$", "$1"));

removes last occurrence of the 'xxx' if it is last:

    System.out.println("aaa xxx aaa  ".replaceAll("xxx\\s*$", ""));

you can replace the 'xxx' on what you want but watch out on special chars

Solution 14 - Java

 // creating StringBuilder
 StringBuilder builder = new StringBuilder(requestString);
 // removing last character from String
 builder.deleteCharAt(requestString.length() - 1);

Solution 15 - Java

How can a simple task be made complicated. My solution is:

public String removeLastChar(String s) {
    return s[0..-1]
}

or

public String removeLastChar(String s) {
    if (s.length() > 0) {
        return s[0..-1]
    }
    return s
}

Solution 16 - Java

Look to StringBuilder Class :

	StringBuilder sb=new StringBuilder("toto,");
	System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"

Solution 17 - Java

A one-liner answer (just a funny alternative - do not try this at home, and great answers already given):

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

Solution 18 - Java

// Remove n last characters  
// System.out.println(removeLast("Hello!!!333",3));

public String removeLast(String mes, int n) {
    return mes != null && !mes.isEmpty() && mes.length()>n
         ? mes.substring(0, mes.length()-n): mes;
}

// Leave substring before character/string  
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));

public String leaveBeforeChar(String mes, String last) {
    return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
         ? mes.substring(0, mes.lastIndexOf(last)): mes;
}

Solution 19 - Java

Most answers here forgot about surrogate pairs.

For instance, the character 핫 (codepoint U+1D56B) does not fit into a single char, so in order to be represented, it must form a surrogate pair of two chars.

If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1), one splices the surrogate pair, leading to unexpected results.

One should also include a check whether the last character is a surrogate pair:

public static String removeLastChar(String str) {
    Objects.requireNonNull(str, "The string should not be null");
    if (str.isEmpty()) {
        return str;
    }

	char lastChar = str.charAt(str.length() - 1);
	int cut = Character.isSurrogate(lastChar) ? 2 : 1;
	return str.substring(0, str.length() - cut);
}

Solution 20 - Java

Java 8

import java.util.Optional;

public class Test
{
  public static void main(String[] args) throws InterruptedException
  {
    System.out.println(removeLastChar("test-abc"));
  }

  public static String removeLastChar(String s) {
    return Optional.ofNullable(s)
      .filter(str -> str.length() != 0)
      .map(str -> str.substring(0, str.length() - 1))
      .orElse(s);
    }
}

Output : test-ab

Solution 21 - Java

public String removeLastCharacter(String str){
       String result = null;
        if ((str != null) && (str.length() > 0)) {
          return str.substring(0, str.length() - 1);
        }
        else{
            return "";
        }

}

Solution 22 - Java

if we want to remove file extension of the given file,

** Sample code

 public static String removeNCharactersFromLast(String str,int n){
    if (str != null && (str.length() > 0)) {
        return str.substring(0, str.length() - n);
    }

    return "";

}

Solution 23 - Java

if you have special character like ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.

Solution 24 - Java

Why not use the https://docs.oracle.com/javase/tutorial/java/data/characters.html">escape sequence ... !

System.out.println(str + '\b');

Life is much easier now . XD ! ~ A readable one-liner

Solution 25 - Java

I had to write code for a similar problem. One way that I was able to solve it used a recursive method of coding.

static String removeChar(String word, char charToRemove)
{
    for(int i = 0; i < word.lenght(); i++)
    {
        if(word.charAt(i) == charToRemove)
        {
            String newWord = word.substring(0, i) + word.substring(i + 1);
            return removeChar(newWord, charToRemove);
        }
    }

    return word;
}

Most of the code I've seen on this topic doesn't use recursion so hopefully I can help you or someone who has the same problem.

Solution 26 - Java

How to make the char in the recursion at the end:

public static String  removeChar(String word, char charToRemove)
	{
		String char_toremove=Character.toString(charToRemove);
		for(int i = 0; i < word.length(); i++)
		{
			if(word.charAt(i) == charToRemove)
			{
				String newWord = word.substring(0, i) + word.substring(i + 1);
				return removeChar(newWord,charToRemove);
			}
		}
		System.out.println(word);
		return word;
	}

for exemple:

removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"

Solution 27 - Java

Here's an answer that works with codepoints outside of the Basic Multilingual Plane (Java 8+).

Using streams:

public String method(String str) {
	return str.codePoints()
			.limit(str.codePoints().count() - 1)
			.mapToObj(i->new String(Character.toChars(i)))
			.collect(Collectors.joining());
}

More efficient maybe:

public String method(String str) {
	return str.isEmpty()? "": str.substring(0, str.length() - Character.charCount(str.codePointBefore(str.length())));
}

Solution 28 - Java

just replace the condition of "if" like this:

if(a.substring(a.length()-1).equals("x"))'

this will do the trick for you.

Solution 29 - Java

Suppose total length of my string=24 I want to cut last character after position 14 to end, mean I want starting 14 to be there. So I apply following solution.

String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);

Solution 30 - Java

Easy Peasy:

StringBuilder sb= new StringBuilder();
for(Entry<String,String> entry : map.entrySet()) {
		sb.append(entry.getKey() + "_" + entry.getValue() + "|");
}
String requiredString = sb.substring(0, sb.length() - 1);

Solution 31 - Java

For kotlin check out

    val string = "<<<First Grade>>>"
    println(string.drop(6)) // st Grade>>>
    println(string.dropLast(6)) // <<<First Gr
    println(string.dropWhile { !it.isLetter() }) // First Grade>>>
    println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade

Solution 32 - Java

Since Java 11 you can use Optional to avoid null pointer exception and using functional programming:

public String removeLastCharacter(String string) {
    return Optional.ofNullable(string)
        .filter(str -> !str.isEmpty() && !string.isBlank())
        .map(str -> str.substring(0, str.length() - 1))
        .orElse(""); // Should be another value that need if the {@param: string} is "null"
}

Solution 33 - Java

this is well known problem solved beautifully in Perl via chop() and chomp()

long answer here : Java chop and chomp

here is the code :

  //removing trailing characters
  public static String chomp(String str, Character repl) {
    int ix = str.length();
    for (int i=ix-1; i >= 0; i-- ){
      if (str.charAt(i) != repl) break;
      ix = i;
    }
    return str.substring(0,ix);
  }
  
  //hardcut  
  public static String chop(String str) {
    return str.substring(0,str.length()-1);
  }

Solution 34 - Java

If you want to remove specific character at the end you could use:

myString.removeSuffix("x")

Solution 35 - Java

Simple Kotlin way:

if (inputString.isNotEmpty()) {
    inputString.dropLast(1) // You can define how many chars you want to remove
}

Refer to the official doc here

Solution 36 - Java

This is the one way to remove the last character in the string:

Scanner in = new Scanner(System.in);
String s = in.nextLine();
char array[] = s.toCharArray();
int l = array.length;
for (int i = 0; i < l-1; i++) {
    System.out.print(array[i]);
}

Solution 37 - Java

u can do i hereString = hereString.replace(hereString.chatAt(hereString.length() - 1) ,' whitespeace');

Solution 38 - Java

Use StringUtils.Chop(Str) it also takes care of null and empty strings, u need to import common-io:

	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.8.0</version>
	</dependency>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionduaprog137View Question on Stackoverflow
Solution 1 - JavaGyan aka Gary BuynView Answer on Stackoverflow
Solution 2 - JavaFahim ParkarView Answer on Stackoverflow
Solution 3 - JavaiddqdView Answer on Stackoverflow
Solution 4 - JavaMart135688View Answer on Stackoverflow
Solution 5 - JavaBobBobBobView Answer on Stackoverflow
Solution 6 - JavamembersoundView Answer on Stackoverflow
Solution 7 - JavaMahavir JainView Answer on Stackoverflow
Solution 8 - JavaNavaneethView Answer on Stackoverflow
Solution 9 - JavaMike SamuelView Answer on Stackoverflow
Solution 10 - JavaKasturiView Answer on Stackoverflow
Solution 11 - JavaDonosoView Answer on Stackoverflow
Solution 12 - JavaGanesa VijayakumarView Answer on Stackoverflow
Solution 13 - JavaArkadiusz CieślińskiView Answer on Stackoverflow
Solution 14 - JavaBachan JosephView Answer on Stackoverflow
Solution 15 - JavatstempkoView Answer on Stackoverflow
Solution 16 - JavaaeocomView Answer on Stackoverflow
Solution 17 - JavaNick LouloudakisView Answer on Stackoverflow
Solution 18 - JavaOleksandr PaldypanidaView Answer on Stackoverflow
Solution 19 - JavaMC EmperorView Answer on Stackoverflow
Solution 20 - JavaNadhuView Answer on Stackoverflow
Solution 21 - JavaC WilliamsView Answer on Stackoverflow
Solution 22 - JavaVasanthakumar JagannathanView Answer on Stackoverflow
Solution 23 - JavaMoadKeyView Answer on Stackoverflow
Solution 24 - JavaTilak MaddyView Answer on Stackoverflow
Solution 25 - JavaJacob MehnertView Answer on Stackoverflow
Solution 26 - Javasimon francisView Answer on Stackoverflow
Solution 27 - JavaPatrick ParkerView Answer on Stackoverflow
Solution 28 - JavaSyed Salman HassanView Answer on Stackoverflow
Solution 29 - JavaAvinash KhadsanView Answer on Stackoverflow
Solution 30 - JavaRoboCView Answer on Stackoverflow
Solution 31 - JavaklvnmarshallView Answer on Stackoverflow
Solution 32 - JavaDenilson AnachuryView Answer on Stackoverflow
Solution 33 - JavastenView Answer on Stackoverflow
Solution 34 - JavaIvo StoyanovView Answer on Stackoverflow
Solution 35 - JavaShailendra MaddaView Answer on Stackoverflow
Solution 36 - Javaalagu rajaView Answer on Stackoverflow
Solution 37 - Javaabd akView Answer on Stackoverflow
Solution 38 - JavaBaha' Al-KhateibView Answer on Stackoverflow