用其他数组字符串替换数组字符串

时间:2013-11-27 02:32:56

标签: java

相同主题:replace String with another in java

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

我有Array A = {NewCounter, NewCounter2, NewCounter3}
说我有Array B = {test, testA, testB}

我希望将数组A替换为字符串B中的数组Replace
我尝试使用方法 ReplaceAll(A.get(index), B.get(index));

问题是:

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

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

但我必须更改String Replace之前:

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

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

Thanksfull,

-mazipan -

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

如果SUM只是一个字符串而不是方法,那么您可以使用:

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

如果Sum是一种方法,那么你可以使用

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

虽然对于第二个,你可能需要通过用

包围它来转换/转换为字符串
().toString()

或添加

(String)()

答案 2 :(得分:0)

Apache的commons-lang StringUtils#replaceEach优雅地处理这些问题。

可运行代码:

public static void main(String [] args) {
     String replace = "SUM(NewCounter)+SUM(NewCounter2)+NewCounter3";
     String [] a = { "NewCounter", "NewCounter2", "NewCounter3" };
     String [] b = { "test", "testA", "testB" };

     System.out.println(StringUtils.replaceEach(replace, a, b));
}

会给你

SUM(test)+SUM(test2)+test3