【发布时间】:2014-08-07 16:19:53
【问题描述】:
我希望在一个区间内将一个字符串拆分为一个字符串数组,但我不希望将单词切成两半。例如:
说文本是:
Lorem Ipsum Sub Rosa Dolores Clairborne. The quick brown fox zipped quickly to the tall yellow fence and hopped to the other side.
Interval: 50
会分为以下几部分
separated[0]: "Lorem Ipsum Sub Rosa Dolores Clairborne. The quick brown"
separated[1]: "fox zipped quickly to the tall yellow fence and"
separated[2]: "hopped to the other side."
我一直在尝试解决这个问题,我想出的最好的方法是:
private static String[] splitMessage(String text, int interval) {
char[] splitText = text.toCharArray();
String[] message = new String[(int) Math.ceil(((text.length() / (double)interval)))];
int indexOfSpace = 0, previousIndex = 0, messageCursor = 0, pos = 0;
for (int i = 0; i < splitText.length-1; i++) {
if (splitText[i] == ' ') {
indexOfSpace = i;
}
if (pos == interval) {
message[messageCursor] = text.substring(previousIndex, indexOfSpace);
previousIndex = indexOfSpace;
messageCursor++;
}
pos++;
}
return message;
}
这最终只会将 Lorem 拆分为第一个索引。有什么建议吗?
【问题讨论】: