b6a56faaef812d85c327d836cd2bb0b8d53a81cc.svn-base 3.2 KB

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