可能重复:
在Java中将字符串拆分为相等长度的子字符串
鉴于以下实用方法,我有:
/**
* Splits string <tt>s</tt> into chunks of size <tt>chunkSize</tt>
*
* @param s the string to split; must not be null
* @param chunkSize number of chars in each chuck; must be greater than 0
* @return The original string in chunks
*/
public static List<String> splitInChunks(String s, int chunkSize) {
Preconditions.checkArgument(chunkSize > 0);
List<String> result = Lists.newArrayList();
int length = s.length();
for (int i = 0; i < length; i += chunkSize) {
result.add(s.substring(i, Math.min(length, i + chunkSize)));
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
1)在任何常见的Java库(例如Apache Commons,Google Guava )中是否存在等效方法,所以我可以将其从代码库中删除?找不到快速的样子.它是返回一个数组还是一个字符串列表并不重要.
(显然我不会为了这个而添加依赖于某个庞大的框架,但是随意提及任何常见的lib;也许我已经使用它了.)
2)如果没有,是否有一些更简单,更清晰的方法在Java中执行此操作?还是一种性能显着提升的方式?(如果您建议使用基于正则表达式的解决方案,请考虑非正则表达专家的可读性清洁度...... :-)
编辑:这有资格作为问题"将字符串拆分为Java中的等长子串 "的副本,因为这个Guava解决方案完美地回答了我的问题!
Sea*_*oyd 14
你可以用Guava的Splitter做到这一点:
Splitter.fixedLength(chunkSize).split(s)
Run Code Online (Sandbox Code Playgroud)
...返回一个Iterable<String>.
这个答案中还有一些例子.