java我想在特定长度后拆分一个字符串,而不剪切任何单词,而不是相等的字符串
我想把一根绳子分开,比如“贰佰肆拾壹元陆角捌卢比整”,当它的长度是35时,我想把这根绳子分成两半。我尝试了这个代码来分割字符串
String text = "Rupees Two Hundred Forty One and Sixty Eight only";
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += 35) {
parts.add(text.substring(i, Math.min(length, i + size)));
但是输出是这样的
[Rupees Two Hundred Forty One and Si, xty Eight only]
但我想像这样分开绳子
[Rupees Two Hundred Forty One and, Sixty Eight only]
拆分字符串时没有剪切词。 根据账单金额,字符串每次都会变化
# 1 楼答案
只需在
i+35
位置搜索首选位置。要考虑的一件事是,当没有这样的位置,即单词超过指定的大小时,应该发生什么。下面的代码将执行大小限制,如果找不到好的位置,则在单词的中间断裂:如果中断发生在空格字符处,则将从结果字符串中删除空格
# 2 楼答案
您可以找到“and”的索引,并将字符串从0子串到“and”的索引
# 3 楼答案
我将使用
StringBuilders
从头开始构建字符串。下面是一个例子,里面有一些评论:哪些输出到:
# 4 楼答案
我认为可以使用
while
循环来计算包含最后一个空格字符的单词:演示:
# 5 楼答案
你可能无法完全做到这一点。但是使用字符串。indexOf()查找从35开始的第一个空格。然后使用substring方法分割字符串
这里有另一种方法。尚未对边境案件进行全面检查