Split string to equal length substrings in Java

后端 未结 21 1838
日久生厌
日久生厌 2020-11-22 02:56

How to split the string \"Thequickbrownfoxjumps\" to substrings of equal size in Java. Eg. \"Thequickbrownfoxjumps\" of 4 equal size should give th

21条回答
  •  [愿得一人]
    2020-11-22 03:19

    This is very easy with Google Guava:

    for(final String token :
        Splitter
            .fixedLength(4)
            .split("Thequickbrownfoxjumps")){
        System.out.println(token);
    }
    

    Output:

    Theq
    uick
    brow
    nfox
    jump
    s
    

    Or if you need the result as an array, you can use this code:

    String[] tokens =
        Iterables.toArray(
            Splitter
                .fixedLength(4)
                .split("Thequickbrownfoxjumps"),
            String.class
        );
    

    Reference:

    • Splitter.fixedLength()
    • Splitter.split()
    • Iterables.toArray()

    Note: Splitter construction is shown inline above, but since Splitters are immutable and reusable, it's a good practice to store them in constants:

    private static final Splitter FOUR_LETTERS = Splitter.fixedLength(4);
    
    // more code
    
    for(final String token : FOUR_LETTERS.split("Thequickbrownfoxjumps")){
        System.out.println(token);
    }
    

提交回复
热议问题