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

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

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


当前回答

从Java 8开始,你可以使用Optional来避免空指针异常,并使用函数式编程:

public String removeLastCharacter(String string) {
    return Optional.ofNullable(string)
        .filter(str -> !str.isEmpty() && !string.isBlank())
        .map(str -> str.substring(0, str.length() - 1))
        .orElse(""); // Should be another value that need if the {@param: string} is "null"
}

其他回答

Java 8

import java.util.Optional;

public class Test
{
  public static void main(String[] args) throws InterruptedException
  {
    System.out.println(removeLastChar("test-abc"));
  }

  public static String removeLastChar(String s) {
    return Optional.ofNullable(s)
      .filter(str -> str.length() != 0)
      .map(str -> str.substring(0, str.length() - 1))
      .orElse(s);
    }
}

输出:test-ab

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

就可读性而言,我认为这是最简洁的

StringUtils.substring("string", 0, -1);

负索引可以在Apache的StringUtils实用程序中使用。 所有负数都从字符串末尾开始偏移处理。

kotlin检查

string.dropLast(1)
 // creating StringBuilder
 StringBuilder builder = new StringBuilder(requestString);
 // removing last character from String
 builder.deleteCharAt(requestString.length() - 1);