Split a String Every n Characters in Java – 在Java中每隔n个字符分割一个字符串

最后修改: 2022年 1月 3日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’re going to shed light on how to split a string every n characters in Java.

在本教程中,我们将阐明如何在Java中n个字符拆分一个字符串

First, we’ll start by exploring possible ways to do this using built-in Java methods. Then, we’re going to showcase how to achieve the same objective using Guava.

首先,我们将开始探索使用内置的Java方法来实现这一目标的可能方法。然后,我们将展示如何使用Guava来实现同样的目标。

2. Using the String#split Method

2.使用String#split方法

The String class comes with a handy method called split. As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression.

String类带有一个方便的方法,称为split顾名思义它根据给定的分隔符或正则表达式将一个字符串分割成多个部分。

Let’s see it in action:

让我们看看它的行动。

public static List<String> usingSplitMethod(String text, int n) {
    String[] results = text.split("(?<=\\G.{" + n + "})");

    return Arrays.asList(results);
}

As we can see, we used the regex (?<=\\G.{” + n + “}) where n is the number of characters. It’s a positive lookbehind assertion that matches a string that has the last match (\G) followed by n characters.

正如我们所看到的,我们使用了regex (?<=\G.{” + n + “}) 其中n 是字符的数量。这是一个positive lookbehind断言,它匹配一个最后一个匹配(\G)后面有n字符的字符串

Now, let’s create a test case to check that everything works as expected:

现在,让我们创建一个测试用例,以检查一切工作是否符合预期。

public class SplitStringEveryNthCharUnitTest {

    public static final String TEXT = "abcdefgh123456";

    @Test
    public void givenString_whenUsingSplit_thenSplit() {
        List<String> results = SplitStringEveryNthChar.usingSplitMethod(TEXT, 3);

        assertThat(results, contains("abc", "def", "gh1", "234", "56"));
    }
}

3. Using the String#substring Method

3.使用String#substring方法

Another way to split a String object at every nth character is to use the substring method.

另一种在每第n个字符处分割String对象的方式是使用substring方法。

Basically, we can loop through the string and call substring to divide it into multiple portions based on the specified n characters:

基本上,我们可以循环浏览字符串并调用substring,根据指定的n字符将其分成多个部分。

public static List<String> usingSubstringMethod(String text, int n) {
    List<String> results = new ArrayList<>();
    int length = text.length();

    for (int i = 0; i < length; i += n) {
        results.add(text.substring(i, Math.min(length, i + n)));
    }

    return results;
}

As shown above, the substring method allows us to get the part of the string between the current index i and i+n.

如上所示,substring方法允许我们获得当前索引ii+n.之间的字符串部分。

Now, let’s confirm this using a test case:

现在,让我们用一个测试案例来确认这一点。

@Test
public void givenString_whenUsingSubstring_thenSplit() {
    List<String> results = SplitStringEveryNthChar.usingSubstringMethod(TEXT, 4);

    assertThat(results, contains("abcd", "efgh", "1234", "56"));
}

4. Using the Pattern Class

4.使用Pattern

Pattern offers a concise way to compile a regular expression and match it against a given string.

Pattern 提供了一种简明的方式来编译正则表达式并与给定的字符串进行匹配。

So, with the correct regex, we can use Pattern to achieve our goal:

因此,有了正确的重码,我们可以使用Pattern来实现我们的目标。

public static List<String> usingPattern(String text, int n) {
    return Pattern.compile(".{1," + n + "}")
        .matcher(text)
        .results()
        .map(MatchResult::group)
        .collect(Collectors.toList());
}

As we can see, we used “.{1,n}” as the regex to create our Pattern object. It matches at least one and at most n characters.

正如我们所看到的,我们使用“.{1,n}”作为重码来创建我们的Pattern对象它至少匹配一个,最多匹配n个字符。

Lastly, let’s write a simple test:

最后,让我们写一个简单的测试。

@Test
public void givenString_whenUsingPattern_thenSplit() {
    List<String> results = SplitStringEveryNthChar.usingPattern(TEXT, 5);

    assertThat(results, contains("abcde", "fgh12", "3456"));
}

5. Using Guava

5.使用番石榴

Now that we know how to split a string every n characters using core Java methods, let’s see how to do the same thing using the Guava library:

现在我们知道了如何使用核心Java方法将一个字符串每n个字符分割开来,让我们看看如何使用Guava库来做同样的事情。

public static List<String> usingGuava(String text, int n) {
    Iterable<String> parts = Splitter.fixedLength(n).split(text);

    return ImmutableList.copyOf(parts);
}

Guava provides the Splitter class to simplify the logic of extracting substrings from a string. The fixedLength() method splits the given string into pieces of the specified length.

Guava提供了Splitter类来简化从字符串中提取子串的逻辑。fixedLength() 方法将给定的字符串分割成指定长度的片段

Let’s verify our method with a test case:

让我们用一个测试案例来验证我们的方法。

@Test
public void givenString_whenUsingGuava_thenSplit() {
    List<String> results = SplitStringEveryNthChar.usingGuava(TEXT, 6);

    assertThat(results, contains("abcdef", "gh1234", "56"));
}

6. Conclusion

6.结语

To sum it up, we explained how to split a string at every nth character using Java methods.

综上所述,我们解释了如何使用Java方法在每第n个字符处分割一个字符串。

After that, we showed how to accomplish the same goal using the Guava library.

之后,我们展示了如何使用Guava库来完成同样的目标。

As always, the code used in this article can be found over on GitHub.

一如既往,本文中所使用的代码可以在GitHub上找到over