Java Map Replace replace(String s, Map map)

Here you can find the source of replace(String s, Map map)

Description

replace

License

Open Source License

Declaration

public static String replace(String s, Map<String, Object> map) 

Method Source Code


//package com.java2s;
import java.util.Map;

public class Main {

    public static String replace(String s, Map<String, Object> map) {
        StringBuilder ret = new StringBuilder((int) (s.length() * 1.5));
        int cursor = 0;
        for (int start, end; (start = s.indexOf("${", cursor)) != -1 && (end = s.indexOf("}", start)) != -1;) {
            ret.append(s.substring(cursor, start)).append(map.get(s.substring(start + 2, end)));
            cursor = end + 1;//from   w ww . j a  v  a 2s . co m
        }
        ret.append(s.substring(cursor, s.length()));
        return ret.toString();
    }

    public static String replace(String s, Object... objs) {
        if (objs == null || objs.length == 0)
            return s;
        if (s.indexOf("{}") == -1)
            return s;
        StringBuilder ret = new StringBuilder((int) (s.length() * 1.5));
        int cursor = 0;
        int index = 0;
        for (int start; (start = s.indexOf("{}", cursor)) != -1;) {
            ret.append(s.substring(cursor, start));
            if (index < objs.length) {
                ret.append(objs[index]);
            } else {
                ret.append("{}");
            }
            cursor = start + 2;
            index++;
        }
        ret.append(s.substring(cursor, s.length()));
        return ret.toString();
    }
}

Related

  1. replace(Map map, String content)
  2. replace(Map map, String text)
  3. replace(String originalCommand, Map vars)
  4. replace(String orign, Map replaceStringMap)
  5. replace(String src, String prefix, String suffix, Map props)
  6. replace(String str, Map values)
  7. replace(String string, Map values)
  8. replace(String target, Map arguments)