Home » Java » How to remove the last character from a string?

How to remove the last character from a string?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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.

Answers:

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;
}

Questions:
Answers:

Why not just one liner?

private static String removeLastChar(String str) {
    return str.substring(0, str.length() - 1);
}

Full Code

import java.util.*;
import java.lang.*;

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) + "==");

    }

    private static String removeLastChar(String str) {
        return str.substring(0, str.length() - 1);
    }
}

Demo

Questions:
Answers:

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

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

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

Questions:
Answers:

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”

Questions:
Answers:

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

Questions:
Answers:

Use this:

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

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

Questions:
Answers:
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”.

Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options.

Questions:
Answers:

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.

Questions:
Answers:

Look to StringBuilder Class :

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

Questions:
Answers:

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;}

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

Questions:
Answers:

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

Questions:
Answers:
// 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;
}

Questions:
Answers:

Why not use the escape sequence … !

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

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

Questions:
Answers:

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

Questions:
Answers:

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]);
}

Questions:
Answers:
 "String name" = "String name".substring(0, ("String name".length() - 1));

Im 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 name".length() > 0) {
    "String name" = "String name".substring(0, ("String name".length() - 1));
}