将String拆分为指定长度的块(除了最后一个)

时间:2014-07-09 02:31:14

标签: java string split

假设我有以下字符串:

String = "0123456789abcdefg";

如何将其拆分为5个块,以便我得到一个像

这样的字符串数组
["01234", "56789", "abcde", "fg"]

请注意,最后一个字符串长度为2个字符。

在Java中有一种简单的方法吗?

2 个答案:

答案 0 :(得分:3)

//UNTESTED CODE!!
String in = "0123456789abcdefg";
List<String> blocks = new ArrayList<String>();

int i = 0;
for ( ; i < (in.length()-5) ; i += 5) { //while there are more than 5 characters remaining 
    blocks.add(in.substring(i, (i+5) ); 
}

blocks.add(in.substring(i, in.length()) //add any remaining characters 

答案 1 :(得分:1)

我想substring方法应该足以达到您的目的,例如:

final int CHUNK_SIZE = 5;
List<String> chunks = new ArrayList<String>();

for (int i = 0; i*CHUNK_SIZE < string.length() - 1; ++i)
  chunks.add(string.substring(i*chunkSize,Math.min((i+1)*chunkSize, string.length())));