我想从字符串中删除最后一个字符。我试过这样做:

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

获取字符串的长度- 1,并将最后一个字母替换为空(删除它),但每次我运行程序时,它都会删除与最后一个字母相同的中间字母。

例如,单词是“仰慕者”;在我运行这个方法之后,我得到了“钦佩”。我想让它回复“钦佩”这个词。


当前回答

我不得不为类似的问题编写代码。我解决这个问题的一种方法是用递归的编码方法。

static String removeChar(String word, char charToRemove)
{
    for(int i = 0; i < word.lenght(); i++)
    {
        if(word.charAt(i) == charToRemove)
        {
            String newWord = word.substring(0, i) + word.substring(i + 1);
            return removeChar(newWord, charToRemove);
        }
    }

    return word;
}

我所见过的关于这个主题的大多数代码都没有使用递归,所以希望我可以帮助您或有相同问题的人。

其他回答

为什么不只是一条航线呢?

public static String removeLastChar(String str) {
    return removeLastChars(str, 1);
}

public static String removeLastChars(String str, int chars) {
    return str.substring(0, str.length() - chars);
}

完整代码

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) + "==");
    }
    
    public static String removeLastChar(String str) {
        return removeLastChars(str, 1);
    }

    public static String removeLastChars(String str, int chars) {
        return str.substring(0, str.length() - chars);
    }
}

Demo

不要试图重新发明轮子,而其他人已经编写了库来执行字符串操作: org.apache.commons.lang3.StringUtils.chop ()

所描述的问题和提出的解决方案有时涉及到移除分隔器。如果这是你的情况,那么看看Apache Commons StringUtils,它有一个叫做removeEnd的方法,非常优雅。

例子:

StringUtils.removeEnd("string 1|string 2|string 3|", "|");

会导致: "string 1|string 2|string 3"

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

kotlin检查

string.dropLast(1)