Java-递归方式替换字符串中的多个占位符参数,类似String.format(%s)
public static void main(String[] args) {
String str = "当前有{}人";
str = assembleParam(str,3);
System.out.println(str);
str = "当前有{}人,参数1:{},参数2:{}";
str = assembleParam(str,3,"张三","李四");
System.out.println(str);
str = assembleParam(str,Lists.newArrayList(3,"张三","李四"));
System.out.println(str);
}
private final static String PARAMS_PLACEHOLDER = "{}";
private final static String PARAMS_PLACEHOLDER_4_PATTERN = "\\" + PARAMS_PLACEHOLDER;
//递归方式替换字符串中的多个占位符参数,类似String.format(%s)
public static String assembleParam(String string, Object... params) { // List<String> params 可以给成 String... params
return doAssembleParam(string, 0, params);
}
public static String assembleParam(String string, List<Object> params) {
Object[] paramArr = params.toArray();
return doAssembleParam(string, 0, paramArr);
}
//私有
private static String doAssembleParam(String string, int paramIdx, Object... params) {
if (params == null || params.length == 0 || paramIdx + 1 > params.length || StringUtils.isBlank(string) || !string.contains(PARAMS_PLACEHOLDER)) {
return string;
}
string = string.replaceFirst(PARAMS_PLACEHOLDER_4_PATTERN, String.valueOf(params[paramIdx]));
if (string.contains(PARAMS_PLACEHOLDER)) {
return doAssembleParam(string, ++paramIdx, params);
}
return string;
}
正文到此结束