首页 > 其他 > 详细

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

时间:2018-07-29 17:22:47      阅读:186      评论:0      收藏:0      [点我收藏+]

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;
    }

 

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

原文:https://www.cnblogs.com/TIMHY/p/9385934.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!