Skip to content
Advertisement

How to remove the last character from a string?

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.

Advertisement

Answer

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