我有一个长度为 n 的单行字符串,我想将其分成最多 3 行。每行最多可以有 45 个字符,之后我想添加一个换行符(“\n”)。第 3 行最多可以有 42 个字符,如果字符串超过 42 个字符,之后我需要包含 3 个点 (...),从而使第 3 行中的总字符数也为 45。
条件是换行符不能加在单词中间。我如何有效地做到这一点?这个操作只是整个程序的一小部分,但会被反复调用。所以我不确定我是否真的应该关心效率。
我现在正在做的是首先弄清楚单词之间的空格在哪里,然后将其添加到列表中。然后我遍历列表并找到 3 个索引,每个索引代表每行的结束词。所以第一个索引将是最接近 45 的空格,下一个最接近 90,第三个最接近 135。然后我使用这些索引来拆分实际的字符串,并分别添加“\n”和“...”。这是我的代码:
//maxCharsPerLine will be 45
public String splitString(String input, int maxCharsPerLine){
String output = "";
ArrayList<Integer> spaces = new ArrayList<Integer>();
// Logic to figure out after which word the sentence should be split so that we don't split in middle of a word
for(int index = 0; index < input.length(); index++){
if(input.charAt(index)==' '){
spaces.add(index);
}
}
//add index of last word of string
spaces.add(input.length());
int index1 = 0; int index2 = 0; int index3 = 0;
for(Integer index : spaces){
// find word closest to and less than maxCharsPerLine. This index will be used to find the last word in line1
if(index<=maxCharsPerLine)
index1 = index;
// find word closest to and less than 2*maxCharsPerLine. This index will be used to find the last word in line2
else if(index<=2*maxCharsPerLine)
index2 = index;
// find word closest to and less than 3*maxCharsPerLine, but exclude 3 chars for adding the dots (...). This index will be used to find the last word in line3
else if(index<=(3*maxCharsPerLine)-3)
index3 = index;
}
if(input.length()>maxCharsPerLine){
if(index1 > 0)
output = input.substring(0, index1);
if(index2 > 0)
output += "\n"+input.substring(index1+1, index2);
if(index3 > 0){
output += "\n"+input.substring(index2+1, index3);
if(input.length()>3*maxCharsPerLine)
output += "...";
}
}
//if length of input is < 45, just return the input
else
output = input;
return output;
}
不确定在哪些情况下会失败。有更好的方法吗?
谢谢。
最佳答案
如果不考虑3点换行,可以使用Apache Commons Lang的WordUtils.wrap
方法。
WordUtils.wrap(str, 45)
关于java - 在 Java 中将字符串分成多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604752/