替换模板字符串中的变量
    如 $amount$元$amountName$
    根据输入参数 amount 1999 amountName 红包
    输出 1999元红包

    1. public static String replaceTemplateParams(String templateContent, Map<String, String> extMap) {
    2. List<String> paramList = pickDynamicParamList(templateContent);
    3. StringBuilder stringBuilder = new StringBuilder();
    4. int startIndex = 0;
    5. for (String param : paramList) {
    6. String value = extMap.get(StringUtil.trim(param, '$'));
    7. if (StringUtils.isBlank(value)) {
    8. value = "";
    9. }
    10. int index = templateContent.indexOf(param, startIndex);
    11. stringBuilder.append(templateContent, startIndex, index);
    12. stringBuilder.append(value);
    13. startIndex = index + param.length();
    14. }
    15. stringBuilder.append(templateContent.substring(startIndex));
    16. return stringBuilder.toString();
    17. }
    18. private static List<String> pickDynamicParamList(String templateContent) {
    19. List<String> result = Lists.newArrayList();
    20. int startIndex = 0;
    21. int endIndex = 0;
    22. boolean enterDynamic = false;
    23. char[] chars = templateContent.toCharArray();
    24. for (int i = 0; i < chars.length; i++) {
    25. if ('$' != chars[i]) {
    26. continue;
    27. }
    28. if (!enterDynamic) {
    29. startIndex = i;
    30. enterDynamic = true;
    31. } else {
    32. endIndex = i;
    33. enterDynamic = false;
    34. }
    35. if (!enterDynamic) {
    36. String params = String.valueOf(Arrays.copyOfRange(chars, startIndex, endIndex + 1));
    37. result.add(params);
    38. }
    39. }
    40. return result;
    41. }
    42. public static String trim(String str, char c) {
    43. char[] chars = str.toCharArray();
    44. int len = chars.length;
    45. int st = 0;
    46. while ((st < len) && (chars[st] == c)) {
    47. st++;
    48. }
    49. while ((st < len) && (chars[len - 1] == c)) {
    50. len--;
    51. }
    52. return (st > 0) && (len < chars.length) ? str.substring(st, len) : str;
    53. }
    54. public static void main(String[] args) {
    55. String templateContent = "$amount$元$amountName$";
    56. Map<String, String> extMap = new HashMap<>();
    57. extMap.put("amount", "1999");
    58. extMap.put("amountName", "红包");
    59. System.out.println(replaceTemplateParams(templateContent, extMap));
    60. }