gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:41:47 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

你想要:

newTitleSearch = new String(temp);

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

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

关于java - 增加字符串的最后一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4002021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com