0 votes
1 view
in Java by (900 points)

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.

1 Answer

0 votes
by (13.2k points)

  You are using replace() whose purpose is to remove all the instances of 

   that letter. To remove the last letter you can follow these ways -

  1. Using StringUtils.chop()

This function is the easiest way to remove the last character, as this functions sole purpose is to do that.It just requires the string as the parameter.

It works on empty and Null strings as well.

public String method(String str) {

StringUtils.chop(str);

return str;

}

  1. Using StringUtils.substring()

This is the same as your replace(), with the only difference that it will replace the character from the position mentioned only and not all of its occurrence.

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;

}

...