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

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

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


当前回答

使用StringUtils.Chop(Str),它也会处理null和空字符串,你需要导入common-io:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.8.0</version>
    </dependency>

其他回答

既然我们讨论的是一个主题,我们也可以使用正则表达式

"aaabcd".replaceFirst(".$",""); //=> aaabc  

你可以做我 hereString = hereString.replace(hereString. chatat (hereString.length() - 1),' whitespeace');

查看StringBuilder类:

    StringBuilder sb=new StringBuilder("toto,");
    System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"

如何在最后的递归中创建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"

在Kotlin中,您可以使用字符串类的dropLast()方法。 它会从字符串中删除给定的数字,返回一个新的字符串

var string1 = "Some Text"
string1 = string1.dropLast(1)