gpt4 book ai didi

java - 用其他多个字符替换Java中的多个字符?

转载 作者:行者123 更新时间:2023-12-01 16:57:51 24 4
gpt4 key购买 nike

我看到有一些与此类似的问题,但那里的答案并没有真正帮助我。不管怎样,我有一个像这样的字符串“今天是星期六”。我需要将每个字符“a”更改为“b”,将每个字符“o”更改为“f”。基本上,用多个字符替换多个字符。现在,我尝试做这样的事情:

String string.replace("a","b").replace("o","f");

但它只进行第一次替换。我尝试过使用 Stringbuilder:

stringBuilder.append(string);
for (int i=0; i<stringBuilder.length(); i++){
char c=stringBuilder.charAt(i);
if (c=='a'){
I don't know how to replace it here to 'b'...
}
}

stringBuilder.toString();

我读过我可以使用 map ,但我以前从未使用过它们,也不知道该怎么做。谁能帮我解决这个问题吗?

最佳答案

听起来您想要一个类似于 SQL TRANSLATE 函数的方法。

public static String translate(String input, String fromChars, String toChars) {
if (fromChars.isEmpty() || fromChars.length() != toChars.length())
throw new IllegalArgumentException();
if (input == null || input.isEmpty())
return input;
char[] buf = input.toCharArray();
for (int i = 0; i < buf.length; i++) {
char ch = buf[i];
for (int j = 0; j < fromChars.length(); j++) {
if (fromChars.charAt(j) == ch) {
buf[i] = toChars.charAt(j);
break;
}
}
}
return new String(buf);
}

测试

System.out.println(translate("Today is Saturday", "ao", "bf"));

输出

Tfdby is Sbturdby
<小时/>

这是一个使用 Map 的版本,它支持来自补充平面的 Unicode 字符,例如表情符号:

public static String translate(String input, String fromChars, String toChars) {
// Build codepoint mapping table
if (fromChars.isEmpty() || fromChars.length() < toChars.length()) {
throw new IllegalArgumentException("fromChars cannot be shorter than toChars (" +
fromChars.length() + " < " + toChars.length() + ")");
}
Map<Integer, String> map = new HashMap<>();
for (int fromIdx = 0, fromEnd, toIdx = 0; fromIdx < fromChars.length(); fromIdx = fromEnd) {
fromEnd = fromChars.offsetByCodePoints(fromIdx, 1);
String mapped = "";
if (toIdx < toChars.length()) {
int toEnd = toChars.offsetByCodePoints(toIdx, 1);
mapped = toChars.substring(toIdx, toEnd);
toIdx = toEnd;
}
if (map.put(fromChars.codePointAt(fromIdx), mapped) != null) {
throw new IllegalArgumentException("Duplicate value in fromChars at index " + fromIdx + ": " +
fromChars.substring(fromIdx, fromEnd));
}
}

// Map codepoints
if (input == null || input.isEmpty())
return input;
StringBuilder buf = new StringBuilder();
for (int idx = 0, end; idx < input.length(); idx = end) {
end = input.offsetByCodePoints(idx, 1);
String mapped = map.get(input.codePointAt(idx));
buf.append(mapped != null ? mapped : input.substring(idx, end));
}
return buf.toString();
}

测试

System.out.println(translate("Today is Saturday 😀", "ao😀r", "bf😕"));

输出

Tfdby is Sbtudby 😕

请注意如何删除 r,因为 toCharsfromChars 短。这就是 SQL TRANSLATE 函数的工作原理。

关于java - 用其他多个字符替换Java中的多个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61557671/

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