gpt4 book ai didi

java - 如何替换某个角色的某个实例

转载 作者:行者123 更新时间:2023-12-02 05:25:23 25 4
gpt4 key购买 nike

当我想替换某个字符时,我不知道如何替换它,它只是替换字符串中的所有实例。我尝试过的事情

String s = "thaba" //I want to replace h with a and vice versa along with b and a
for (int i; i < s.length; i++)
if (s.substring(i, i+1).equalsIngoreCase("a")) {
s = s.replace(s.substring(i, i + 1), s.substring(i - 1, i));
s = s.replace(s.substring(i - 1, i), s.substring(i, i + 1));
}

问题在于它的出现

thhbb

尽管我希望它能出现这样的情况:

tahab

或者如果我输入

thaflar

我想让它输出

tahfalr

我知道为什么会发生这种情况,但我不知道如何让它仅替换那些实例如有任何帮助,我们将不胜感激。

修复

我对这个问题的意思不同,我在上面修正了,它的措辞有些不正确

最佳答案

我会编写一个方法并使用 String.indexOf()String.substring()替换每个字符的第一次出现,例如

public static String replaceFirst(String in, char a, char b) {
int pos1 = in.indexOf(a);
int pos2 = in.indexOf(b);
if (pos2 < pos1) {
int temp = pos2;
pos2 = pos1;
pos1 = temp;
}
StringBuilder sb = new StringBuilder();
if (pos1 != -1 && pos2 != -1 && pos1 != pos2) {
sb.append(in.substring(0, pos1));
sb.append(b);
sb.append(in.substring(pos1 + 1, pos2));
sb.append(a);
sb.append(in.substring(pos2 + 1));
} else {
sb.append(in);
}
return sb.toString();
}

然后你可以用类似的方式调用它

public static void main(String[] args) {
String s = "tha";
System.out.println(replaceFirst(s, 'h', 'a'));
}

输出是所请求的

tah

编辑

为了支持您请求的其他功能,您还必须跟踪起始位置。首先,我们可以将以前的方法委托(delegate)给新方法,如下所示 -

public static String replaceFirst(String in, char a, char b) {
return replaceFirst(in, 0, a, b);
}

然后,我们只需调用 indexOf(char, int) 来指定最小索引 -

public static String replaceFirst(String in, int start, char a, char b) {
int pos1 = in.indexOf(a, start);
int pos2 = in.indexOf(b, start);
StringBuilder sb = new StringBuilder();
if (pos1 != -1 && pos2 != -1 && pos1 != pos2) {
if (pos2 < pos1) {
int temp = pos2;
pos2 = pos1;
pos1 = temp;
}
sb.append(in.substring(0, pos1));
sb.append(b);
sb.append(in.substring(pos1 + 1, pos2));
sb.append(a);
sb.append(in.substring(pos2 + 1));
} else {
sb.append(in);
}
return sb.toString();
}

最后,我们可以调用它

public static void main(String[] args) {
String s = "afab";
s = replaceFirst(s, 'a', 'f');
s = replaceFirst(s, 2, 'a', 'b');
System.out.println(s);
}

哪些输出

faba

关于java - 如何替换某个角色的某个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26091046/

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