如何将一个字符串拆分成具有最大字符长度的相等部分,同时保持单词边界?
比如说,如果我想将字符串"hello world"拆分为最大7个字符的相等子字符串,则应该返回:
"hello "
和
"world"
但是我的当前实现返回
"hello w"
和
"orld "
我正在使用从Split string to equal length substrings in Java获取的以下代码来将输入字符串分成相等的部分。
public static List<String> splitEqually(String text, int size) {
// Give the list the right capacity to start with. You could use an array
// instead if you wanted.
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
在将字符串分成子字符串时,是否可以保持单词边界?
更具体地说,我需要字符串分割算法考虑由空格提供的单词边界,而不仅仅依靠字符长度进行字符串分割,尽管字符长度也需要考虑,但更像是字符的最大范围,而不是硬编码的字符长度。