4 回答

TA贡献1825条经验 获得超6个赞
你可能无法完全做到这一点。但是使用 String.indexOf() 找到从 35 开始的第一个空格。然后使用 substring 方法来划分字符串。
String text = "Rupees Two Hundred Forty One and Sixty Eight only";
int i = text.indexOf(" ", 35);
if (i < 0) {
i = text.length();
}
String part1 = text.substring(0,i).trim();
String part2 = text.substring(i).trim();
这是一种替代方法。尚未对边境案件进行全面检查。
String[] words = text.split(" ");
int k;
part1 = words[0];
for (k = 1; k < words.length; k++) {
if (part1.length() >= 35 - words[k].length()) {
break;
}
part1 += " " + words[k];
}
if (k < words.length) {
part2 = words[k++];
while (k < words.length) {
part2 += " " + words[k++];
}
}
System.out.println(part1);
System.out.println(part2);

TA贡献1847条经验 获得超7个赞
只需在该职位上搜索首选职位即可i+35。需要考虑的一件事是,当没有这样的位置时,即单词超过指定的大小时,会发生什么。以下代码将强制执行大小限制,如果找不到合适的位置,则会在单词中间中断:
List<String> parts = new ArrayList<>();
int size = 35, length = text.length();
for(int i = 0, end, goodPos; i < length; i = end) {
end = Math.min(length, i + size);
goodPos = text.lastIndexOf(' ', end);
if(goodPos <= i) goodPos = end; else end = goodPos + 1;
parts.add(text.substring(i, goodPos));
}
如果中断发生在空格字符处,则该空格将从结果字符串中删除。

TA贡献1780条经验 获得超1个赞
我认为您可以使用while循环来计算包含最后一个空格字符的单词:
public static List<String> split(String str, int length) {
List<String> res = new ArrayList<>();
int prvSpace = 0;
int from = 0;
while (prvSpace < str.length()) {
int pos = str.indexOf(' ', prvSpace + 1);
if (pos == -1) {
res.add(str.substring(from));
prvSpace = str.length();
} else if (pos - from < length)
prvSpace = pos;
else {
res.add(str.substring(from, prvSpace));
from = prvSpace + 1;
}
}
return res;
}
演示:
in: "RupeesTwoHundredFortyOneandSixtyEightonly"
out: ["RupeesTwoHundredFortyOneandSixtyEightonly"]
in: "Rupees Two Hundred Forty One and Sixty Eight only"
out: ["Rupees Two Hundred Forty One and", "Sixty Eight only"]

TA贡献1846条经验 获得超7个赞
我找到了使用 Apache commons-lang3 的替代方案:
import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
class Example {
public static void main(String[] args) {
String text = "Rupees Two Hundred Forty One and Sixty Eight only";
String wrappedText = WordUtils.wrap(text, 35, "\n", false);
String[] lines = StringUtils.split(wrappedText, "\n");
System.out.println(Arrays.asList(lines));
// Outputs [Rupees Two Hundred Forty One and, Sixty Eight only]
}
}
注意。如果您的输入有换行符,最好将其删除。
添加回答
举报