1. Overview
1.概述
In this short tutorial, we’ll explore different ways of getting the first n characters of a string in Java.
在这个简短的教程中,我们将探讨用 Java 获取字符串前 n 个字符的不同方法。
First, we’ll learn how to do this using core JDK methods and classes. Then, we’ll see how to achieve the same outcome using external libraries such as Apache Commons Lang and Guava.
首先,我们将学习如何使用 JDK 核心方法和类实现这一目标。然后,我们将了解如何使用外部库(如 Apache Commons Lang 和 Guava )实现相同的结果。
2. Using Core JDK
2.使用核心 JDK
JDK provides several methods that we can use to get the first n characters of a given string. So, let’s take a close look at each option.
JDK 提供了几种方法,我们可以用它们来获取给定字符串的前 n 个字符。那么,让我们仔细看看每个选项。
2.1. Using String#substring Method
2.1.使用 String#substring 方法
The substring() method belongs to the String class and offers the easiest solution to answer our central question. As the name implies, this method returns as a new string a subset of the given string.
substring() 方法属于 String 类,它为回答我们的中心问题提供了最简单的解决方案。顾名思义,该方法返回给定字符串的子集作为新字符串。
So, let’s see it in action:
那么,让我们来看看它的实际效果吧:
@Test
void givenString_whenUsingSubstringMethod_thenGetFirstChars() {
String givenInput = "Hello Baeldung Readers";
assertEquals("He", givenInput.substring(0, 2));
}
The method accepts two arguments, beginIndex and endIndex. beginIndex denotes the index of the first character and endIndex represents the last index which is exclusive.
该方法接受两个参数:beginIndex 和 endIndex 。beginIndex表示第一个字符的索引,endIndex表示最后一个索引,它是排他的。
With that being said, the returned substring starts at the specified endIndex and extends to the character at the index endIndex – 1.
也就是说,返回的子字符串从指定的 endIndex 开始,延伸至索引 endIndex – 1 处的字符。
2.2. Using String#subSequence Method
2.2.使用 String#subSequence 方法
Another solution would be to use the subSequence() method. It returns a CharSequence object that holds a portion of the specified string.
另一种解决方案是使用 subSequence() 方法。该方法会返回一个 CharSequence 对象,其中包含指定字符串的一部分。
The invocation of subSequence(start, end) behaves exactly like the invocation of the substring(start, end) method. So, let’s see it in action:
调用 subSequence(start, end) 的行为与调用 substring(start, end) 方法的行为完全相同。那么,让我们来看看它的实际应用:
@Test
void givenString_whenUsingSubSequenceMethod_thenGetFirstChars() {
String givenInput = "Welcome";
assertEquals("Wel", givenInput.subSequence(0, 3));
}
Similarly, the method returns the first three characters “Wel” of the string “Welcome”. We should remember that this method throws IndexOutOfBoundsException if beginIndex or endIndex is negative, or if endIndex is greater than the string length, or when beginIndex is greater than endIndex.
同样,该方法返回字符串 “Welcome”的前三个字符 “Wel”。我们应该记住,如果 beginIndex 或 endIndex 为负值,或 endIndex 大于字符串长度,或 beginIndex 大于 endIndex 时,该方法将抛出 IndexOutOfBoundsException 。
2.3. Using String#chars Method
2.3.使用 String#chars 方法
The String class provides the chars() as another option to retrieve the first n characters. This new method is introduced in Java 9 to manipulate a given string as a Stream.
String 类提供了 chars() 作为另一种检索前 n 个字符的方法。在 Java 9 中引入了这个新方法,可将给定字符串作为 Stream 进行操作。
So, let’s exemplify the use of the chars() method using another test case:
因此,让我们使用另一个测试用例来示范 chars() 方法的使用:
@Test
void givenString_whenUsingStreamApi_thenGetFirstChars() {
String givenInput = "The world is beautiful";
String result = givenInput.chars()
.limit(3)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
assertEquals("The", result);
}
In a nutshell, chars() returns an IntStream holding the char values of the string input. Furthermore, we used the limit(3) method to retrieve the first three values. Then, we used collect() with StringBuilder to build a string from the returned values.
简而言之,chars() 返回一个 IntStream 字符串输入的 char 值。此外,我们使用 limit(3) 方法来检索前三个值。然后,我们使用collect()和 StringBuilder从返回的值中构建一个字符串。
3. Using Apache Commons Lang
3.使用 Apache Commons 语言
Alternatively, we can use the Apache Commons Lang library to tackle our challenge. It comes with a set of utility classes, such as StringUtils, that we can use to perform string operations.
或者,我们可以使用 Apache Commons Lang 库来解决我们的难题。它提供了一系列实用程序类,例如 StringUtils ,我们可以使用它们来执行字符串操作。
First, let’s add its dependency to the pom.xml file:
首先,将 依赖关系添加到 pom.xml 文件中:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
3.1. Using StringUtils#substring Method
3.1.使用 StringUtils#substring 方法
Typically, StringUtils provides its version of the substring() method. The particularity of this method is that it’s null-safe compared to String#substring:
通常,StringUtils 会提供其版本的 substring() 方法。与 String#substring 相比,该方法的特殊性在于它是空安全的:
@Test
void givenString_whenUsingStringUtilsSubstringMethod_thenGetFirstChars() {
String givenInput = "Baeldung";
assertEquals("Baeld", StringUtils.substring(givenInput, 0, 5));
}
As shown above, the returned substring “Baeld” starts with the character in the position zero and ends before the position 5.
如上图所示,返回的子串 “Baeld” 从位置 0 的字符开始,在位置 5 之前结束。
3.2. Using StringUtils#left Method
3.2.使用 StringUtils#left 方法
Similarly, we can use the left() method to accomplish the same outcome. This method returns the leftmost n characters of the given string.
同样,我们可以使用 left() 方法来实现相同的结果。该方法返回给定字符串最左边的 n 个字符。
So, let’s illustrate how to use StringUtils#left using a practical example:
因此,让我们用一个实际例子来说明如何使用 StringUtils#left :
@Test
void givenString_whenUsingStringUtilsLeftMethod_thenGetFirstChars() {
String givenInput = "kindness always wins";
assertEquals("kind", StringUtils.left(givenInput, 4));
}
The good thing about this method is that it’s null-safe as it returns null if the specified string input is null.
该方法的优点是它是空安全的,因为如果指定的字符串输入为 null 则返回 null。
4. Using Guava
4.使用番石榴
Another solution would be using the Guava. As usual, before starting to work with this library, we need to add its dependency to pom.xml:
另一种解决方案是使用 Guava。像往常一样,在开始使用该库之前,我们需要将其依赖关系添加到pom.xml中:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.0.0-jre</version>
</dependency>
Guava provides the Ascii#truncate method that we can use as a workaround to get the first characters of a string:
Guava提供了Ascii#truncate方法,作为一种变通方法,我们可以使用该方法获取字符串的第一个字符:
@Test
void givenString_whenUsingGuavaTruncateMethod_thenGetFirstChars() {
String givenInput = "Tamassint";
assertEquals("Tama", Ascii.truncate(givenInput, 4, ""));
}
In short, this method truncates the given string to the specified maximum length of 4 in our case.
简而言之,该方法会将给定的字符串截断到指定的最大长度4。
5. Conclusion
5.结论
In this short article, we explored various ways of getting the first n characters of a given string in Java.
在这篇短文中,我们探讨了用 Java 获取给定字符串前 n 个字符的各种方法。
Along the way, we saw how to use JDK methods and classes. Then, we learned how to achieve the same objective using external libraries such as Apache Commons Lang and Guava.
在学习过程中,我们了解了如何使用 JDK 方法和类。然后,我们学习了如何使用 Apache Commons Lang 和 Guava 等外部库实现相同的目标。
As always, the code used in this article can be found over on GitHub.