Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, 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.

Java bottom

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

>> CHECK OUT THE COURSE
Generic footer banner
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!