Named placeholders in string formatting

后端 未结 20 2151
情话喂你
情话喂你 2020-11-27 10:16

In Python, when formatting string, I can fill placeholders by name rather than by position, like that:

print \"There\'s an incorrect value \'%(value)s\' in c         


        
20条回答
  •  执笔经年
    2020-11-27 11:05

    You could have something like this on a string helper class

    /**
     * An interpreter for strings with named placeholders.
     *
     * For example given the string "hello %(myName)" and the map 
     *      

    Map map = new HashMap();

    *

    map.put("myName", "world");

    *
    * * the call {@code format("hello %(myName)", map)} returns "hello world" * * It replaces every occurrence of a named placeholder with its given value * in the map. If there is a named place holder which is not found in the * map then the string will retain that placeholder. Likewise, if there is * an entry in the map that does not have its respective placeholder, it is * ignored. * * @param str * string to format * @param values * to replace * @return formatted string */ public static String format(String str, Map values) { StringBuilder builder = new StringBuilder(str); for (Entry entry : values.entrySet()) { int start; String pattern = "%(" + entry.getKey() + ")"; String value = entry.getValue().toString(); // Replace every occurence of %(key) with value while ((start = builder.indexOf(pattern)) != -1) { builder.replace(start, start + pattern.length(), value); } } return builder.toString(); }

提交回复
热议问题