我有一个长度为 n 的单行字符串,我想将其分成最多 3 行。每行最多可以有 45 个字符,之后我想添加一个换行符(“\n”)。第 3 行最多可以有 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;
}
Run Code Online (Sandbox Code Playgroud)
不确定在哪些情况下这会失败。有一个更好的方法吗?
谢谢。