I want to erase the last character from the string, how do I do it?

Asked 2 years ago, Updated 2 years ago, 126 views

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

I tried to erase the last character from the string. This also eliminates intermediate characters, such as the last character in the string.

For example, there's a string called admir, and if you turn the method, it's not admir, but admie. What should I do?

string java

2022-09-22 22:22

1 Answers

The replace method replaces all of the characters. So you'd better use the substring.

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


2022-09-22 22:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.