java - 在 Java 中将字符串分成多行

标签 java algorithm

我有一个长度为 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/

相关文章:

java - 是否有任何算法可以将大约 40k 字符减少为 2-3k 字符?

c - 不明白 Codility CountDiv 解法是如何正确的

algorithm - 计算最严格的 Big-Oh 循环边界

algorithm - 我相信这个算法在 O(n^3) 时间内运行。正确的?

algorithm - 选择着色算法

java - 从整数到整数的 AES 加密

java - 在另一个 View 周围的圆圈中动态添加 View

java - 从 TD/B HTML 标记中提取文本,xpath ="//table[@class=' 表']/tbody/tr[1]/td

java - 我在这个算法上做错了什么?

algorithm - 在 ns2 中实现时 TORA 出错