1. Introduction
1.介绍
Java 12 added a couple of useful APIs to the String class. In this tutorial, we will explore these new APIs with examples.
Java 12 为String类添加了几个有用的 API。在本教程中,我们将通过实例探讨这些新的 API。
2. indent()
2.indent()
The indent() method adjusts the indentation of each line of the string based on the argument passed to it.
indent()方法根据传递给它的参数,调整字符串每一行的缩进。
When indent() is called on a string, the following actions are taken:
当对一个字符串调用indent()时,会采取以下行动。
- The string is conceptually separated into lines using lines(). lines() is the String API introduced in Java 11.
- Each line is then adjusted based on the int argument n passed to it and then suffixed with a line feed “\n”.
- If n > 0, then n spaces are inserted at the beginning of each line.
- If n < 0, then up to n white space characters are removed from the beginning of each line. In case a given line does not contain sufficient white space, then all leading white space characters are removed.
- If n == 0, then the line remains unchanged. However, line terminators are still normalized.
- The resulting lines are then concatenated and returned.
For example:
比如说。
@Test
public void whenPositiveArgument_thenReturnIndentedString() {
String multilineStr = "This is\na multiline\nstring.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(3);
assertThat(postIndent, equalTo(outputStr));
}
We can also pass a negative int to reduce the indentation of the string. For example:
我们还可以传递一个负的int来减少字符串的缩进。比如说。
@Test
public void whenNegativeArgument_thenReturnReducedIndentedString() {
String multilineStr = " This is\n a multiline\n string.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(-2);
assertThat(postIndent, equalTo(outputStr));
}
3. transform()
3.transform()
We can apply a function to this string using the transform() method. The function should expect a single String argument and produce a result:
我们可以使用transform()方法对this字符串应用一个函数。该函数应该期待一个String参数并产生一个结果。
@Test
public void whenTransformUsingLamda_thenReturnTransformedString() {
String result = "hello".transform(input -> input + " world!");
assertThat(result, equalTo("hello world!"));
}
It is not necessary that the output has to be a string. For example:
输出不一定是一个字符串。比如说。
@Test
public void whenTransformUsingParseInt_thenReturnInt() {
int result = "42".transform(Integer::parseInt);
assertThat(result, equalTo(42));
}
4. Conclusion
4.结论
In this article, we explored the new String APIs in Java 12. As usual, code snippets can be found over on GitHub.
在这篇文章中,我们探讨了Java 12中新的String APIs。像往常一样,可以在GitHub上找到代码片段。