# string
# Apache 提供的一个工具类 StringUtils
commons-lang 有两个版本,一个是 commons-lang3 ,一个是 commons-lang 。
commons-lang 是老版本,已经很久没有维护了。
commons-lang3 是一直在维护的版本,推荐直接使用这个版本。
# 判断字符串是否为空
StringUtils.isBlank(" ");//true
1
# 字符串固定长度
这个通常用于字符串需要固定长度的场景,比如需要固定长度字符串作为流水号,若流水号长度不足,,左边补 0 。
这里当然可以使用 String#format 方法,不过比较麻烦
int i1 = 45;
int i2 = 456769795;
String s3 = "45";
String s4 = "454567845";
System.out.println(String.format("%06d",i1));
System.out.println(String.format("%06d",i2));
System.out.println(String.format("%6s",s3));
System.out.println(String.format("%6s",s4));
System.out.println(StringUtils.leftPad(s3,6,"P"));
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
000045;
456769795;
45;
454567845;
PPPP45;
1
2
3
4
5
2
3
4
5
# 字符串关键字替换
// 默认替换所有关键字
StringUtils.replace("aba", "a", "z") = "zbz";
// 替换关键字,仅替换一次
StringUtils.replaceOnce("aba", "a", "z") = "zba";
// 使用正则表达式替换
StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123";
1
2
3
4
5
6
2
3
4
5
6
# 字符串拼接
StringUtils.join(["a", "b", "c"], ",") = "a,b,c"
1
String[] array = new String[]{"test", "1234", "5678"};
List<String> list=new ArrayList<>();
list.add("test");
list.add("1234");
list.add("5678");
StringUtils.join(array, ",");
// 逗号分隔符,跳过 null
Joiner joiner=Joiner.on(",").skipNulls();
joiner.join(array);
joiner.join(list);
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 字符串拆分
StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
StringUtils.splitByWholeSeparatorPreserveAllTokens("a..b.c", ".")= ["a","", "b", "c"]
1
2
2
Splitter splitter = Splitter.on(",");
// 返回是一个 List 集合,结果:[ab, , b, c]
splitter.splitToList("ab,,b,c");
// 忽略空字符串,输出结果 [ab, b, c]
splitter.omitEmptyStrings().splitToList("ab,,b,c")
1
2
3
4
5
2
3
4
5
# 12 个精致的 Java 字符串操作小技巧
# 如何判断一个字符串是前后对称的
/**
* 是否对称
*/
private boolean checkSymmetry(String str) {
boolean result = true;
if (StringUtils.isNotBlank(str)) {
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str.charAt(i) != str.charAt(length - i - 1)) {
result = false;
break;
}
}
}
return result;
}
@Test
public void testSymmetry() {
String s1 = "htring";
String s2 = "htringnirth";
String s3 = "htringgnirth";
System.out.println(s1+"对称吗? "+checkSymmetry(s1));
System.out.println(s2+"对称吗? "+checkSymmetry(s2));
System.out.println(s3+"对称吗? "+checkSymmetry(s3));
}
// htring对称吗? false
// htringnirth对称吗? true
// htringgnirth对称吗? true
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
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
# 如何在字符串中获取不同的字符及其数量
@Test
public void testCalc() {
System.out.println(calculateCharCout("htringlimin"));
System.out.println(calculateCharCout("choubaogudou"));
}
/**
* 计算字符串中不同字符的数量
*
* @param str 待处理字符串
* @return 字符与数量键值对
*/
private static Map<Character, Integer> calculateCharCout(String str) {
Map<Character, Integer> maps = Maps.newLinkedHashMap();
if (StringUtils.isNotBlank(str)) {
Stopwatch stopwatch = Stopwatch.createStarted();
for (char c : str.toCharArray()) {
Integer currentCount = maps.get(c);
Integer nextCount = currentCount == null ? 1 : Integer.sum(currentCount, 1);
maps.put(c, nextCount);
}
System.out.println("处理时间:\t" + stopwatch.elapsed(TimeUnit.NANOSECONDS) + "ns");
}
return maps;
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
处理时间:289700ns
{h=1, t=1, r=1, i=3, n=2, g=1, l=1, m=1}
处理时间:150400ns
{c=1, h=1, o=3, u=3, b=1, a=1, g=1, d=1}
1
2
3
4
2
3
4
JDK 8 出现以后,简洁了,但是性能似乎弱一些;
/**
* 计算字符串中不同字符的数量(JDK 8)
*
* @param str 待处理字符串
* @return 字符与数量键值对
*/
private static Map<Character, Integer> calculateCharCount8(String str) {
Map<Character, Integer> maps = Maps.newLinkedHashMap();
if (StringUtils.isNotBlank(str)) {
Stopwatch stopwatch = Stopwatch.createStarted();
for (char c : str.toCharArray()) {
maps.merge(c, 1, Integer::sum);
}
System.out.println("JDK 8处理时间:\t" + stopwatch.elapsed(TimeUnit.NANOSECONDS) + "ns");
}
return maps;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
处理时间:283400ns
{h=1, t=1, r=1, i=3, n=2, g=1, l=1, m=1}
JDK 8处理时间:46232400ns
{h=1, t=1, r=1, i=3, n=2, g=1, l=1, m=1}
处理时间:10000ns
{c=1, h=1, o=3, u=3, b=1, a=1, g=1, d=1}
JDK 8处理时间:27000ns
{c=1, h=1, o=3, u=3, b=1, a=1, g=1, d=1}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 字符串去除各种空白字符
# JAVA 中去掉首尾空格
String.trim()
1
# 去掉所有空格,包括首尾、中间
replaceAll(" ", "");
String str = " hell o ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2);
1
2
3
4
5
2
3
4
5
replaceAll(" +","");
1
replaceAll("\\s*", "");
1
可以替换大部分空白字符, 不限于空格(\s 可以匹配空格、制表符、换页符等空白字符的其中任意一个)
# 字符串模板替换
# 1、使用内置String.format
String message = String.format("您好%s,晚上好!您目前余额:%.2f元,积分:%d", "张三", 10.155, 10);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
1
2
3
2
3
# 2、使用内置MessageFormat
String message = MessageFormat.format("您好{0},晚上好!您目前余额:{1,number,#.##}元,积分:{2}", "张三", 10.155, 10);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
1
2
3
2
3