4 回答

TA貢獻1825條經(jīng)驗 獲得超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條經(jīng)驗 獲得超7個贊
只需在該職位上搜索首選職位即可i+35。需要考慮的一件事是,當(dāng)沒有這樣的位置時,即單詞超過指定的大小時,會發(fā)生什么。以下代碼將強制執(zhí)行大小限制,如果找不到合適的位置,則會在單詞中間中斷:
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));
}
如果中斷發(fā)生在空格字符處,則該空格將從結(jié)果字符串中刪除。

TA貢獻1780條經(jīng)驗 獲得超1個贊
我認為您可以使用while循環(huán)來計算包含最后一個空格字符的單詞:
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條經(jīng)驗 獲得超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]
}
}
注意。如果您的輸入有換行符,最好將其刪除。
添加回答
舉報