Split string to equal length substrings in Java

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

    A StringBuilder version:

    public static List getChunks(String s, int chunkSize)
    {
     List chunks = new ArrayList<>();
     StringBuilder sb = new StringBuilder(s);
    
    while(!(sb.length() ==0)) 
    {           
       chunks.add(sb.substring(0, chunkSize));
       sb.delete(0, chunkSize);
    
    }
    return chunks;
    

    }

提交回复
热议问题