Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

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

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.

2. Using the String#split Method

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.

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.

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

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

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

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.

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

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

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

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.

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

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:

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.

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

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

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

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

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.