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