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

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,并将最后一个字母替换为空(删除它),但每次我运行程序时,它都会删除与最后一个字母相同的中间字母。

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


当前回答

如果你有特殊的性格喜欢;在json中只需使用string .replace(";", ""),否则你必须重写字符串中的所有字符减去最后一个。

其他回答

 string = string.substring(0, (string.length() - 1));

我在我的代码中使用这个,它很容易和简单。 它只在字符串为> 0时起作用。 我把它连接到一个按钮和下面的if语句

if (string.length() > 0) {
    string = string.substring(0, (string.length() - 1));
}

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

例子:

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

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

一个简单的回答(只是一个有趣的选择-不要在家里尝试,并且已经给出了很好的答案):

public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}

如何在最后的递归中创建char:

public static String  removeChar(String word, char charToRemove)
    {
        String char_toremove=Character.toString(charToRemove);
        for(int i = 0; i < word.length(); i++)
        {
            if(word.charAt(i) == charToRemove)
            {
                String newWord = word.substring(0, i) + word.substring(i + 1);
                return removeChar(newWord,charToRemove);
            }
        }
        System.out.println(word);
        return word;
    }

为例:

removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"
// Remove n last characters  
// System.out.println(removeLast("Hello!!!333",3));

public String removeLast(String mes, int n) {
    return mes != null && !mes.isEmpty() && mes.length()>n
         ? mes.substring(0, mes.length()-n): mes;
}

// Leave substring before character/string  
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));

public String leaveBeforeChar(String mes, String last) {
    return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
         ? mes.substring(0, mes.lastIndexOf(last)): mes;
}