1. 引言
在日常开发中,字符串相关的操作非常常见。作为 Java 开发者,掌握这些基础但关键的字符串处理技巧是必不可少的。
本文将为你提供一份快速参考,涵盖 Java 中一些最常用的字符串操作方法,并重点解释 equals
与 ==
的区别、以及 StringUtils.isBlank
和 StringUtils.isEmpty
的差异。
2. 将 char 转换为 String
在 Java 中,一个 char
表示单个字符。但在实际使用中,我们通常需要的是 String
类型。
下面是一个简单的转换方式:
String toStringWithConcatenation(final char c) {
return String.valueOf(c);
}
3. 字符串拼接
另一个常见的需求是将字符串与其他值(如 char
)进行拼接:
String appendWithConcatenation(final String prefix, final char c) {
return prefix + c;
}
也可以使用 StringBuilder
来实现拼接:
String appendWithStringBuilder(final String prefix, final char c) {
return new StringBuilder(prefix).append(c).toString();
}
✅ 使用 StringBuilder
更适合频繁拼接的场景,性能更好。
4. 根据索引获取字符
如果需要从字符串中提取某个位置的字符,可以使用如下方法:
char getCharacterByIndex(final String text, final int index) {
return text.charAt(index);
}
⚠️ 注意:字符串内部是以 char[]
存储的,索引从 0 开始。
5. 处理 ASCII 值
我们可以通过类型转换在 char
和其对应的 ASCII 值之间切换:
int asciiValue(final char character) {
return (int) character;
}
char fromAsciiValue(final int value) {
Assert.isTrue(value >= 0 && value < 65536, "value is not a valid character");
return (char) value;
}
⚠️ 注意:int
是 4 字节,而 char
是 2 字节,所以要确保传入的值在合法范围内。
6. 去除所有空白字符
有时候我们需要去除字符串中的空白字符,使用正则表达式配合 replaceAll
是个好办法:
String removeWhiteSpace(final String text) {
return text.replaceAll("\\s+", "");
}
✅ 这个方法可以清除所有空白字符,包括空格、换行、制表符等。
7. 将集合拼接为字符串
当我们有一个集合(如 List),需要将其元素拼接成一个字符串时,可以用以下方式:
<T> String fromCollection(final Collection<T> collection) {
return collection.stream().map(Objects::toString).collect(Collectors.joining(", "));
}
💡 Collectors.joining
还支持指定前缀和后缀,适合构建格式化输出。
8. 字符串分割
使用 split
方法可以按指定分隔符对字符串进行分割:
String[] splitByRegExPipe(final String text) {
return text.split("\\|");
}
⚠️ 因为 split
接受的是正则表达式,如果分隔符是特殊字符(如 |
),需要进行转义。
另一种方式是使用 Pattern.quote()
:
String[] splitByPatternPipe(final String text) {
return text.split(Pattern.quote("|"));
}
✅ 更安全,避免手写转义带来的错误。
9. 将字符串转为字符流处理
如果需要对字符串中的每个字符做详细处理,可以将其转为 IntStream
:
IntStream getStream(final String text) {
return text.chars();
}
💡 这在字符过滤、统计等场景中非常有用。
10. 引用相等 vs 值相等
虽然字符串看起来像基本类型,但其实它是对象。所以我们要区分 引用相等 和 值相等:
==
比较引用是否相同equals()
比较内容是否相同
@Test
public void whenUsingEquals_thenWeCheckForTheSameValue() {
assertTrue("Values are equal", new String("Test").equals("Test"));
}
@Test
public void whenUsingEqualsSign_thenWeCheckForReferenceEquality() {
assertFalse("References are not equal", new String("Test") == "Test");
}
⚠️ 字符串字面量会被放入字符串常量池中,编译器有时会优化为相同引用:
@Test
public void whenTheCompileCanBuildUpAString_thenWeGetTheSameReference() {
assertTrue("Literals are concatenated by the compiler", "Test" == "Te"+"st");
}
11. 空字符串 vs 空白字符串
isEmpty
和 isBlank
有细微差别:
isEmpty
:判断字符串是否为null
或长度为 0isBlank
:判断字符串是否为null
或仅包含空白字符
@Test
public void whenUsingIsEmpty_thenWeCheckForNullorLengthZero() {
assertTrue("null is empty", isEmpty(null));
assertTrue("nothing is empty", isEmpty(""));
assertFalse("whitespace is not empty", isEmpty(" "));
assertFalse("whitespace is not empty", isEmpty("\n"));
assertFalse("whitespace is not empty", isEmpty("\t"));
assertFalse("text is not empty", isEmpty("Anything!"));
}
@Test
public void whenUsingIsBlank_thenWeCheckForNullorOnlyContainingWhitespace() {
assertTrue("null is blank", isBlank(null));
assertTrue("nothing is blank", isBlank(""));
assertTrue("whitespace is blank", isBlank("\t\t \t\n\r"));
assertFalse("test is not blank", isBlank("Anything!"));
}
✅ 使用 isBlank
更符合业务场景中“是否为空”的判断逻辑。
12. 总结
字符串是所有 Java 应用中的核心类型。本文总结了常见的字符串操作方法,并对一些容易混淆的概念进行了澄清。
完整代码示例可参考 GitHub 仓库:GitHub - core-java-string-operations