查找并替换字符串 Find And Replace in String

2018-07-29 17:08:15

问题描述:

问题求解:

字符串替换的问题有个技巧就是从右向左进行替换,这样的话,左边的index就不需要考虑变动了。

    public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
        List<int[]> ls = new ArrayList<>();
        for (int i = 0; i < indexes.length; i++) ls.add(new int[]{indexes[i], i});
        Collections.sort(ls, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[0] - o1[0];
            }
        });
        for (int[] pair : ls) {
            int index = pair[0];
            int i = pair[1];
            String source = sources[i];
            String target = targets[i];
            if (S.substring(index, index + source.length()).equals(source))
                S = S.substring(0, index) + target + S.substring(index + source.length());
        }
        return S;
    }
原文地址:https://www.cnblogs.com/hyserendipity/p/9385934.html