0%

StringUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
...
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
*
* @Description : 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
* @Date: 2021/4/27
*
*/
@Slf4j
public class StringUtils extends org.apache.commons.lang3.StringUtils {

private static final char SEPARATOR = '_';
private static final Charset UTF_8 = StandardCharsets.UTF_8;

/**
* 转换为字节数组
*
* @param str
* @return
*/
public static byte[] getBytes(String str) {
if (str != null) {
return str.getBytes(UTF_8);
} else {
return null;
}
}

public static boolean isEmpty(final String cs) {
if ("null".equalsIgnoreCase(cs)||"undefined".equalsIgnoreCase(cs)) {
return true;
}
return org.apache.commons.lang3.StringUtils.isEmpty(cs);
}

/**
* 转换为字节数组
*
* @param bytes
* @return
*/
public static String toString(byte[] bytes) {
return new String(bytes, UTF_8);
}

/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}

/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
}
return false;
}

/**
* 替换掉HTML标签方法
*/
public static String stripHtml(String html) {
if (isBlank(html)) {
return "";
}
// html.replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "");
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}

/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param html
* @return
*/
public static String toMobileHtml(String html) {
if (html == null) {
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}

/**
* 对txt进行HTML编码,并将\n转换为>br/<、\t转换为   
*
* @param txt
* @return
*/
public static String toHtml(String txt) {
if (txt == null) {
return "";
}
return replace(replace(EncodeUtils.encodeHtml(trim(txt)), "\n", "<br/>"), "\t",
"    ");
}

/**
* 缩略字符串(不区分中英文字符)
*
* @param str 目标字符串
* @param length 截取长度
* @return
*/
public static String abbr(String str, int length) {
if (str == null) {
return "";
}
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
for (char c : stripHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength <= length - 3) {
sb.append(c);
} else {
sb.append("...");
break;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
log.error("UnsupportedEncodingException",e);
}
return "";
}

// 缩略字符串替换Html正则表达式预编译
private static final Pattern p1 = Pattern.compile("<([a-zA-Z]+)[^<>]*>");

/**
* 缩略字符串(适应于与HTML标签的)
*
* @param param 目标字符串
* @param length 截取长度
* @return
*/
public static String htmlAbbr(String param, int length) {
if (param == null) {
return "";
}
StringBuffer result = new StringBuffer();
int n = 0;
char temp;
boolean isCode = false; // 是不是HTML代码
boolean isHTML = false; // 是不是HTML特殊字符,如 
for (int i = 0; i < param.length(); i++) {
temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
n = n - 1;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
try {
if (!isCode && !isHTML) {
n += String.valueOf(temp).getBytes("GBK").length;
}
} catch (UnsupportedEncodingException e) {
log.error("UnsupportedEncodingException",e);
}

if (n <= length - 3) {
result.append(temp);
} else {
result.append("...");
break;
}
}
// 取出截取字符串中的HTML标记
String tempResult = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
// 去掉不需要结素标记的HTML标记
tempResult = tempResult
.replaceAll("</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|"
+ "HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|"
+ "basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|"
+ "option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", "");
// 去掉成对的HTML标记
tempResult = tempResult.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
// 用正则表达式取出标记
Matcher m = p1.matcher(tempResult);
List<String> endHTML = ListUtils.newArrayList();
while (m.find()) {
endHTML.add(m.group(1));
}
// 补全不成对的HTML标记
for (int i = endHTML.size() - 1; i >= 0; i--) {
result.append("</");
result.append(endHTML.get(i));
result.append(">");
}
return result.toString();
}

/**
* 首字母大写
*/
public static String cap(String str) {
return capitalize(str);
}

/**
* 首字母小写
*/
public static String uncap(String str) {
return uncapitalize(str);
}

/**
* 驼峰命名法工具
*
* @return camelCase("hello_world") == "helloWorld" capCamelCase("hello_world") == "HelloWorld"
* uncamelCase("helloWorld") = "hello_world"
*/
public static String camelCase(String s) {
if (s == null) {
return null;
}

s = s.toLowerCase();

StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}

return sb.toString();
}

/**
* 驼峰命名法工具
*
* @return camelCase("hello_world") == "helloWorld" capCamelCase("hello_world") == "HelloWorld"
* uncamelCase("helloWorld") = "hello_world"
*/
public static String capCamelCase(String s) {
if (s == null) {
return null;
}
s = camelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}

/**
* 驼峰命名法工具
*
* @return camelCase("hello_world") == "helloWorld" capCamelCase("hello_world") == "HelloWorld"
* uncamelCase("helloWorld") = "hello_world"
*/
public static String uncamelCase(String s) {
if (s == null) {
return null;
}

StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

boolean nextUpperCase = true;

if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}

if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}

sb.append(Character.toLowerCase(c));
}

return sb.toString();
}

/**
* 转换为JS获取对象值,生成三目运算返回结果
*
* @param objectString 对象串 例如:row.user.id 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
*/
public static String jsGetVal(String objectString) {
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = split(objectString, ".");
for (int i = 0; i < vals.length; i++) {
val.append("." + vals[i]);
result.append("!" + (val.substring(1)) + "?'':");
}
result.append(val.substring(1));
return result.toString();
}

/**
* 获取随机字符串
*
* @param count
* @return
*/
public static String getRandomStr(int count) {
char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9'};
Random random= null;
try {
random = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
log.info("Exception:{}", e.getMessage());
}
if(null == random){
return "";
}
StringBuilder s = new StringBuilder();
for (int i = 0; i < count; i++) {
String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);
s.append(r);
}
return s.toString();
}

/**
* 获取随机数字
*
* @param count
* @return
*/
public static String getRandomNum(int count) {
char[] codeSeq = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
Random random= null;
try {
random = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
log.info("Exception:{}", e.getMessage());
}
if(null == random){
return "";
}
StringBuilder s = new StringBuilder();
for (int i = 0; i < count; i++) {
String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);
s.append(r);
}
return s.toString();
}

/**
* 获取树节点名字
*
* @param isShowCode 是否显示编码<br>
* true or 1:显示在左侧:(code)name<br>
* 2:显示在右侧:name(code)<br>
* false or null:不显示编码:name
* @param code 编码
* @param name 名称
* @return
*/
public static String getTreeNodeName(String isShowCode, String code, String name) {
if ("true".equals(isShowCode) || "1".equals(isShowCode)) {
return "(" + code + ") " + StringUtils.replace(name, " ", "");
} else if ("2".equals(isShowCode)) {
return StringUtils.replace(name, " ", "") + " (" + code + ")";
} else {
return StringUtils.replace(name, " ", "");
}
}

/**
* <p>判断字符串是否是whitespace, empty (""), "null" or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank("null") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
* @param cs 被检测字符串
* @return {@code true} 如果被检测的字符串是null, empty, "null" or whitespace
*/
public static boolean isBlank(final String cs) {
if ("null".equalsIgnoreCase(cs)) {
return true;
}
return org.apache.commons.lang3.StringUtils.isBlank(cs);
}

// 1Mb的二进制长度为20位:1024*1024
private static final int ONE_MB_LENGTH = 20;

public static int getMb(Object obj) {
if (obj == null) {
return 0;
}
byte[] byteArray = getBytes(JsonUtils.toJson(obj));
int byteCount = byteArray == null ? 0 : byteArray.length;
if (byteCount == 0) {
return 0;
}
// size = byteCount / (1*1024*1024)
// 对除的结果进行下取整,1024刚好为2的10次方。采用位运算进行加速处理。
int size = byteCount >> ONE_MB_LENGTH;
return size == 0 ? 1 : size;
}

// 1kb的二进制长度为10位:2的10次方 = 1024
private static final int ONE_KB_LENGTH = 10;

/**
* 获取入参大小
* @param obj
* @return
*/
public static int getKb(Object obj) {
if (null == obj) {
return 0;
}
byte[] byteArray = getBytes(JsonUtils.toJson(obj));
int byteCount = byteArray.length;
if (byteCount == 0) {
return 0;
}
// 对除的结果进行下取整,1024刚好为2的10次方。采用位运算进行加速处理。
int size = byteCount >> ONE_KB_LENGTH;
return size == 0 ? 1 : size;
}

/**
* 截取字符串长度
* @param msg 原始字符串
* @param subLength 要截取的长度
* @return 截取后返回
*/
public static String subString(String msg,int subLength) {
return (msg == null || msg.length() <= subLength) ? msg : msg.substring(subLength);
}
}