StrFormatter.java 3.4 KB

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