Java 中的自动和手动文本换行

问题描述 投票:0回答:1

正如标题所示,我需要在自动和手动模式下用 Java 包装文本(字符串)。对于自动模式,我使用“自动换行”库,它用最大长度的字符换行文本,但我还需要添加手动模式,例如使用键“/”。有人可以帮我吗?

我尝试过使用像“这是一个示例字符串/我需要换行”这样的字符串,并且如果我使用 for 循环来分割字符串,则换行会在之前执行。这是一个例子:

That is an example I need to fix /a example test.

假设手动换行键为“/”,最大字符数为 35。结果将是:

That is an example I need to fix
a example test.

但这是怎么回事:

That is an example I need to fix
a
example test
java text word-wrap
1个回答
0
投票

这是一个演示您想要的方法。

public static final String wrap(String toWrap, String wrapKey, int maxLineLength) {
    String string = new String();
    String[] words = toWrap.split(" ");

    int currentLineLength = 0;
    for (String word : words) {

        // Manual warping
        if(word.contains(wrapKey)) {
            while(word.contains(wrapKey)) 
                word = word.replaceFirst(wrapKey, "\n");
                
            string += word;
                
            continue; // Avoid auto-wrapping
        }
        // Auto warping
        if(currentLineLength + word.length() + 1 <= maxLineLength) {
            string += (word + " ");
            currentLineLength += word.length() + 1;
        }
        else {
            string += ("\n" + word + " ");
            currentLineLength = word.length() + 1;
        }
    }

    return string.trim();
}

像这样使用它

String example = "That is an example I need to fix /a example test.";
        
System.out.println(wrap(example, "/", 35));

你应该得到

That is an example I need to fix 
a
example test.

但是看看 “但是这是怎么回事:” 让我相信这不是你想要的输出,好吧,你的程序和我的程序都没有任何问题,只是 a 和 example 之间的空格是第 35 个字符

That is an example I need to fix /a example test.
                                   ^
                                 35th

或者您可以使用 ApacheCommon 的

WordUtils#wrap
方法

© www.soinside.com 2019 - 2024. All rights reserved.