增加字符串的最后一个字母

Jas*_*son 1 java string

这是我希望 Java 的 String 类有一个 replaceLast 方法的地方,但它没有,而且我的代码得到了错误的结果。

我正在编写一个程序,用于在数据结构中搜索与字符串前缀匹配的任何项目。但是,由于我使用的是迭代器,因此 iter.next() 调用返回的最后一项与模式不匹配,因此我想更改搜索字符串,以便查询的最后一个字符增加一个字母. 我的测试代码返回 [C@b82368 带有此代码和An标题搜索:

public String changeLastCharacter(String titleSearch) {
    char[] temp= titleSearch.toCharArray();

    char lastLetter= temp[temp.length-1];
    lastLetter++;
    temp[temp.length-1]= lastLetter;

    String newTitleSearch= temp.toString();
    return newTitleSearch;
}
Run Code Online (Sandbox Code Playgroud)

首先,这段代码输出的原因是什么?其次,有没有更好的方法来执行我的解决方案?

Mat*_*hen 5

你要:

newTitleSearch = new String(temp);
Run Code Online (Sandbox Code Playgroud)

toString方法不会被数组覆盖;这是通常的Object.toString,用于调试。上面实际上创建了一个字符串。另一种选择是:

int len = titleSearch.length();
String allButLast = titleSearch.substring(0, len - 1);
newTitleSearch = allButLast + new Character(titleSearch.charAt(len - 1) + 1);
Run Code Online (Sandbox Code Playgroud)