1. Introduction
1.绪论
String-based values and operations are quite common in everyday development, and any Java developer must be able to handle them.
基于字符串的值和操作在日常开发中相当常见,任何Java开发者都必须能够处理它们。
In this tutorial, we’ll provide a quick cheat sheet of common String operations.
在本教程中,我们将提供一份常见String操作的快速小抄。
Additionally, we’ll shed some light on the differences between equals and “==” and between StringUtils#isBlank and #isEmpty.
此外,我们将阐明equals和”==”之间的区别,以及StringUtils#isBlank和#isEmpty.的区别。
2. Transforming a Char into a String
2.将一个字符转化为一个字符串
A char represents one character in Java. But in most cases, we need a String.
一个char在Java中代表一个字符。但在大多数情况下,我们需要一个String.。
So let’s start off with transforming chars into Strings:
因此,让我们从将chars转换为Strings开始:。
String toStringWithConcatenation(final char c) {
return String.valueOf(c);
}
3. Appending Strings
3.附加字符串
Another frequently needed operation is appending strings with other values, like a char:
另一个经常需要的操作是用其他值追加字符串,如char。
String appendWithConcatenation(final String prefix, final char c) {
return prefix + c;
}
We can append other basic types with a StringBuilder as well:
我们也可以用StringBuilder附加其他基本类型:。
String appendWithStringBuilder(final String prefix, final char c) {
return new StringBuilder(prefix).append(c).toString();
}
4. Getting a Character by Index
4.通过索引获得一个角色
If we need to extract one character out of a string, the API provides everything we want:
如果我们需要从一个字符串中提取一个字符,该API提供了我们想要的一切。
char getCharacterByIndex(final String text, final int index) {
return text.charAt(index);
}
Since a String uses a char[] as a backing data structure, the index starts at zero.
由于String使用char[] 作为支撑数据结构,索引从零开始。
5. Handling ASCII Values
5.处理ASCII值
We can easily switch between a char and its numerical representation (ASCII) by casting:
我们可以通过转换,在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;
}
Of course, since an int is 4 unsigned bytes and a char is 2 unsigned bytes, we need to check to make sure that we are working with legal character values.
当然,由于一个int是4个无符号字节,一个char是2个无符号字节,我们需要检查以确保我们是在使用合法的字符值。
6. Removing All Whitespace
6.删除所有空白
Sometimes we need to get rid of some characters, most commonly whitespace. A good way is to use the replaceAll method with a regular expression:
有时我们需要去掉一些字符,最常见的是空白。一个好的方法是使用replaceAll方法和regular expression:。
String removeWhiteSpace(final String text) {
return text.replaceAll("\\s+", "");
}
7. Joining Collections to a String
7.将集合连接到一个字符串
Another common use case is when we have some kind of Collection and want to create a string out of it:
另一个常见的用例是当我们有某种Collection并想从中创建一个字符串。
<T> String fromCollection(final Collection<T> collection) {
return collection.stream().map(Objects::toString).collect(Collectors.joining(", "));
}
Notice that the Collectors.joining allows specifying the prefix or the suffix.
注意,Collectors.join允许指定前缀或后缀。
8. Splitting a String
8.分割一个字符串
Or on the other hand, we can split a string by a delimiter using the split method:
或者在另一方面,我们可以使用split方法通过分隔符来分割一个字符串。
String[] splitByRegExPipe(final String text) {
return text.split("\\|");
}
Again, we’re using a regular expression here, this time to split by a pipe. Since we want to use a special character, we have to escape it.
我们在这里再次使用正则表达式,这次是用管子来分割。由于我们要使用一个特殊字符,我们必须转义它。
Another possibility is to use the Pattern class:
另一种可能性是使用Pattern类。
String[] splitByPatternPipe(final String text) {
return text.split(Pattern.quote("|"));
}
9. Processing All Characters as a Stream
9.将所有字符作为一个流处理
In the case of detailed processing, we can transform a string to an IntStream:
在详细处理的情况下,我们可以将一个字符串转换为IntStream。
IntStream getStream(final String text) {
return text.chars();
}
10. Reference Equality and Value Equality
10.参考文献平等和价值平等
Although strings look like a primitive type, they are not.
虽然字符串看起来像一个primitive 类型,但它们不是。
Therefore, we have to distinguish between reference equality and value equality. Reference equality always implies value equality, but in general not the other way around. The first, we check with the ‘==’ operation and the latter, with the equals method:
因此,我们必须区分引用平等和价值平等。引用平等总是意味着价值平等,但一般情况下不是反过来的。 前者,我们用’==’操作检查,后者,用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");
}
Notice that literals are interned in the string pool. Therefore the compiler can at times optimize them to the same reference:
请注意,字面意义是内置于字符串池中的。因此,编译器有时可以将它们优化为同一个引用。
@Test
public void whenTheCompileCanBuildUpAString_thenWeGetTheSameReference() {
assertTrue("Literals are concatenated by the compiler", "Test" == "Te"+"st");
}
11. Blank String vs. Empty String
11.空白字符串与空字符串
There is a subtle difference between isBlank and isEmpty.
isBlank和isEmpty之间有一个微妙的区别。
A string is empty if it’s null or has length zero. Whereas a string is blank if it’s null or contains only whitespace characters:
如果一个字符串是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!"));
}
12. Conclusion
12.结语
Strings are a core type in all kinds of applications. In this tutorial, we learned some key operations in common scenarios.
字符串是各种应用中的核心类型。在本教程中,我们学习了常见情况下的一些关键操作。
Furthermore, we gave directions to more detailed references.
此外,我们还指示了更多详细的参考资料。
Finally, the full code with all examples is available in our GitHub repository.
最后,在我们的GitHub资源库中可以找到包含所有示例的完整代码。