Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k 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 (46k points)

You can try replace, it will replace all occurrences of a letter. All you require to do is apply substring() like this:

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;

}

Hope this helps....!!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...