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

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

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


当前回答

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

其他回答

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

如果你想在结尾删除特定的字符,你可以使用:

myString.removeSuffix("x")

用这个:

 if(string.endsWith("x")) {

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

容易Peasy:

StringBuilder sb= new StringBuilder();
for(Entry<String,String> entry : map.entrySet()) {
        sb.append(entry.getKey() + "_" + entry.getValue() + "|");
}
String requiredString = sb.substring(0, sb.length() - 1);
 // creating StringBuilder
 StringBuilder builder = new StringBuilder(requestString);
 // removing last character from String
 builder.deleteCharAt(requestString.length() - 1);