gpt4 book ai didi

java - 将数组字符串替换为其他数组字符串

转载 作者:行者123 更新时间:2023-12-02 06:29:09 30 4
gpt4 key购买 nike

同一主题:replace String with another in java

我想替换String Replace = "SUM(NewCounter)+SUM(NewCounter2)+NewCounter3";

我有数组 A = {NewCounter, NewCounter2, NewCounter3}
假设我有Array B = {test, testA, testB}

我想用字符串Replace中的数组A和数组B替换它。
我尝试使用方法 ReplaceAll(A.get(index), B.get(index));

问题是:

NewCounter2 被系统读取 "NewCounter"+2
所以我有 result = String Replace = "SUM(test)+SUM(test2)+test3";

我尝试在字符 NewCounter 中使用 ',它将是 Array A = {'NewCounter', 'NewCounter2', 'NewCounter3'}

但我必须像这样更改字符串Replace之前:

String Replace = "SUM('NewCounter')+SUM('NewCounter2')+'NewCounter3'";

我还有其他办法吗???我不想之前更改字符串...

谢谢,

-mazipan-

最佳答案

同时替换的最简单解决方案是按长度递减的顺序处理字符串。这将正确地进行替换:

A = {NewCounter3, NewCounter2, NewCounter}
B = {testB, testA, test}

但是,如果任何搜索字符串可以与替换字符串匹配,则此技术将不起作用。

编辑:对于一般情况,我写了这个:

public static String simultaneousReplace(String subject,
String[] find, String[] replace) {
if (find.length != replace.length) throw new IllegalArgumentException(
"Strings to find and replace are not paired.");
int numPairs = find.length;
StringBuilder sb = new StringBuilder();
for (int i = 0, len = subject.length(); i < len; i++) {
int longestMatchIndex = -1;
int longestMatchLength = -1;
for (int j = 0; j < numPairs; j++) {
String find1 = find[j];
if (subject.regionMatches(false, i, find1, 0, find1.length())) {
if (find1.length() > longestMatchLength) {
longestMatchIndex = j;
longestMatchLength = find1.length();
}
}
}
if (longestMatchIndex >= 0) {
sb.append(replace[longestMatchIndex]);
i += longestMatchLength - 1;
} else {
sb.append(subject.charAt(i));
}
}
return sb.toString();
}

使用示例:

String s = "SUM(NewCounter)+SUM(NewCounter2)+NewCounter3";

s = simultaneousReplace(s,
new String[] { "NewCounter", "NewCounter2", "NewCounter3" },
new String[] { "test", "testA", "testB" }
);

System.out.println(s);

输出:

SUM(test)+SUM(testA)+testB

关于java - 将数组字符串替换为其他数组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20232841/

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