Split string to equal length substrings in Java

后端 未结 21 1858
日久生厌
日久生厌 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:13

    i use the following java 8 solution:

    public static List<String> splitString(final String string, final int chunkSize) {
      final int numberOfChunks = (string.length() + chunkSize - 1) / chunkSize;
      return IntStream.range(0, numberOfChunks)
                      .mapToObj(index -> string.substring(index * chunkSize, Math.min((index + 1) * chunkSize, string.length())))
                      .collect(toList());
    }
    
    0 讨论(0)
  • 2020-11-22 03:16

    Another brute force solution could be,

        String input = "thequickbrownfoxjumps";
        int n = input.length()/4;
        String[] num = new String[n];
    
        for(int i = 0, x=0, y=4; i<n; i++){
        num[i]  = input.substring(x,y);
        x += 4;
        y += 4;
        System.out.println(num[i]);
        }
    

    Where the code just steps through the string with substrings

    0 讨论(0)
  • 2020-11-22 03:18
    public static List<String> getSplittedString(String stringtoSplit,
                int length) {
    
            List<String> returnStringList = new ArrayList<String>(
                    (stringtoSplit.length() + length - 1) / length);
    
            for (int start = 0; start < stringtoSplit.length(); start += length) {
                returnStringList.add(stringtoSplit.substring(start,
                        Math.min(stringtoSplit.length(), start + length)));
            }
    
            return returnStringList;
        }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-11-22 03:19

    Here is a one liner implementation using Java8 streams:

    String input = "Thequickbrownfoxjumps";
    final AtomicInteger atomicInteger = new AtomicInteger(0);
    Collection<String> result = input.chars()
                                        .mapToObj(c -> String.valueOf((char)c) )
                                        .collect(Collectors.groupingBy(c -> atomicInteger.getAndIncrement() / 4
                                                                    ,Collectors.joining()))
                                        .values();
    

    It gives the following output:

    [Theq, uick, brow, nfox, jump, s]
    
    0 讨论(0)
  • 2020-11-22 03:20

    Here's a one-liner version which uses Java 8 IntStream to determine the indexes of the slice beginnings:

    String x = "Thequickbrownfoxjumps";
    
    String[] result = IntStream
                        .iterate(0, i -> i + 4)
                        .limit((int) Math.ceil(x.length() / 4.0))
                        .mapToObj(i ->
                            x.substring(i, Math.min(i + 4, x.length())
                        )
                        .toArray(String[]::new);
    
    0 讨论(0)
提交回复
热议问题