Named placeholders in string formatting

后端 未结 20 2314
情话喂你
情话喂你 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 10:52

    I tried in just a quick way

    public static void main(String[] args) 
    {
        String rowString = "replace the value ${var1} with ${var2}";
        
        Map mappedValues = new HashMap<>();
        
        mappedValues.put("var1", "Value 1");
        mappedValues.put("var2", "Value 2");
        
        System.out.println(replaceOccurence(rowString, mappedValues));
    }
    
    private static  String replaceOccurence(String baseStr ,Map mappedValues)
    {
        for(String key :mappedValues.keySet())
        {
            baseStr = baseStr.replace("${"+key+"}", mappedValues.get(key));
        }
        
        return baseStr;
    }
    

提交回复
热议问题