Replacing multiple substrings in Java when replacement text overlaps search text

前端 未结 5 745
囚心锁ツ
囚心锁ツ 2021-01-12 20:54

Say you have the following string:

cat dog fish dog fish cat

You want to replace all cats with dogs, all do

5条回答
  •  天命终不由人
    2021-01-12 21:43

    public class myreplase {
        public Map replase;
    
        public myreplase() {
            replase = new HashMap();
    
            replase.put("a", "Apple");
            replase.put("b", "Banana");
            replase.put("c", "Cantalope");
            replase.put("d", "Date");
            String word = "a b c d a b c d";
    
            String ss = "";
            Iterator i = replase.keySet().iterator();
            while (i.hasNext()) {
                ss += i.next();
                if (i.hasNext()) {
                    ss += "|";
                }
            }
    
            Pattern pattern = Pattern.compile(ss);
            StringBuilder buffer = new StringBuilder();
            for (int j = 0, k = 1; j < word.length(); j++,k++) {
                String s = word.substring(j, k);
                Matcher matcher = pattern.matcher(s);
                if (matcher.find()) {
                    buffer.append(replase.get(s));
                } else {
                    buffer.append(s);
                }
            }
            System.out.println(buffer.toString());
        }
    
        public static void main(String[] args) {
            new myreplase();
        }
    }
    

    Output :- Apple Banana Cantalope Date Apple Banana Cantalope Date

提交回复
热议问题