Named placeholders in string formatting

后端 未结 20 2289
情话喂你
情话喂你 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:01

    Based on the answer I created MapBuilder class:

    public class MapBuilder {
    
        public static Map build(Object... data) {
            Map result = new LinkedHashMap<>();
    
            if (data.length % 2 != 0) {
                throw new IllegalArgumentException("Odd number of arguments");
            }
    
            String key = null;
            Integer step = -1;
    
            for (Object value : data) {
                step++;
                switch (step % 2) {
                    case 0:
                        if (value == null) {
                            throw new IllegalArgumentException("Null key value");
                        }
                        key = (String) value;
                        continue;
                    case 1:
                        result.put(key, value);
                        break;
                }
            }
    
            return result;
        }
    
    }
    

    then I created class StringFormat for String formatting:

    public final class StringFormat {
    
        public static String format(String format, Object... args) {
            Map values = MapBuilder.build(args);
    
            for (Map.Entry entry : values.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                format = format.replace("$" + key, value.toString());
            }
    
            return format;
        }
    
    }
    

    which you could use like that:

    String bookingDate = StringFormat.format("From $startDate to $endDate"), 
            "$startDate", formattedStartDate, 
            "$endDate", formattedEndDate
    );
    

提交回复
热议问题