2017年4月22日 星期六

[ Java 常見問題 ] Named placeholders in string formatting

Source From Here
Question
In Python, when formatting string, I can fill placeholders by name rather than by position, like that:
  1. print "There's an incorrect value '%(value)s' in column # %(column)d" % \  
  2.   { 'value': x, 'column': y }  
I wonder if that is possible in Java (hopefully, without external libraries)? Thanks in advance.

How-To
StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly. Sample code as below:
  1. Map values = new HashMap();  
  2. values.put("value"1);  
  3. values.put("column"2);  
  4. StrSubstitutor sub = new StrSubstitutor(values, "%("")");  
  5. printf("%s\n", sub.replace("There's an incorrect value '%(value)' in column # %(column)"))  
Output:
There's an incorrect value '1' in column # 2


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...