StrFormatter.java 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package com.ruoyi.common.support;
  2. import com.ruoyi.common.utils.StringUtils;
  3. /**
  4. * 字符串格式化
  5. *
  6. * @author ruoyi
  7. */
  8. public class StrFormatter
  9. {
  10. public static final String EMPTY_JSON = "{}";
  11. public static final char C_BACKSLASH = '\\';
  12. public static final char C_DELIM_START = '{';
  13. public static final char C_DELIM_END = '}';
  14. /**
  15. * 格式化字符串<br>
  16. * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
  17. * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
  18. * 例:<br>
  19. * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
  20. * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
  21. * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
  22. *
  23. * @param strPattern 字符串模板
  24. * @param argArray 参数列表
  25. * @return 结果
  26. */
  27. public static String format(final String strPattern, final Object... argArray)
  28. {
  29. if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
  30. {
  31. return strPattern;
  32. }
  33. final int strPatternLength = strPattern.length();
  34. // 初始化定义好的长度以获得更好的性能
  35. StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
  36. int handledPosition = 0;
  37. int delimIndex;// 占位符所在位置
  38. for (int argIndex = 0; argIndex < argArray.length; argIndex++)
  39. {
  40. delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
  41. if (delimIndex == -1)
  42. {
  43. if (handledPosition == 0)
  44. {
  45. return strPattern;
  46. }
  47. else
  48. { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
  49. sbuf.append(strPattern, handledPosition, strPatternLength);
  50. return sbuf.toString();
  51. }
  52. }
  53. else
  54. {
  55. if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
  56. {
  57. if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
  58. {
  59. // 转义符之前还有一个转义符,占位符依旧有效
  60. sbuf.append(strPattern, handledPosition, delimIndex - 1);
  61. sbuf.append(Convert.utf8Str(argArray[argIndex]));
  62. handledPosition = delimIndex + 2;
  63. }
  64. else
  65. {
  66. // 占位符被转义
  67. argIndex--;
  68. sbuf.append(strPattern, handledPosition, delimIndex - 1);
  69. sbuf.append(C_DELIM_START);
  70. handledPosition = delimIndex + 1;
  71. }
  72. }
  73. else
  74. {
  75. // 正常占位符
  76. sbuf.append(strPattern, handledPosition, delimIndex);
  77. sbuf.append(Convert.utf8Str(argArray[argIndex]));
  78. handledPosition = delimIndex + 2;
  79. }
  80. }
  81. }
  82. // append the characters following the last {} pair.
  83. // 加入最后一个占位符后所有的字符
  84. sbuf.append(strPattern, handledPosition, strPattern.length());
  85. return sbuf.toString();
  86. }
  87. }