如何从字符串中删除最后一个字符? [英] How to remove the last character from a string?

查看:36
本文介绍了如何从字符串中删除最后一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

例如,这个词是崇拜者";运行该方法后,我得到admie".我希望它返回钦佩这个词.

For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.

推荐答案

replace 将替换一个字母的所有实例.您需要做的就是使用 substring():

replace will replace all instances of a letter. All you need to do is use substring():

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

这篇关于如何从字符串中删除最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆