用于将文本行包装到最大行宽的 Java 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4055430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:03:49  来源:igfitidea点击:

Java code for wrapping text lines to a max line width

javatextline-breaksword-wrap

提问by George Armhold

Before I re-invent the wheel (poorly), I'd like to know if there is a some existing Java code for wrapping text lines to a given maximum width. Ideally it would:

在我重新发明轮子(不好)之前,我想知道是否有一些现有的 Java 代码用于将文本行包装到给定的最大宽度。理想情况下,它会:

  • respect existing linebreaks
  • break up lines that exceed a maximum length on word boundaries
  • break up words whose length exceeds the maximum line width by inserting hyphens
  • 尊重现有的换行符
  • 在字边界上分解超过最大长度的行
  • 通过插入连字符拆分长度超过最大行宽的单词

Edit:there are no "pixels" here, only java.lang.String. "maximum width" refers to the number of characters on a line.

编辑:这里没有“像素”,只有 java.lang.String。“最大宽度”是指一行中的字符数。

回答by Ivan P

What you want to do would only work if you display the results with a fixed-width font. Otherwise the number of characters in a line would not be the same from line to line. If that is fine with you, I would say that your's is a fairly uncommon case (especially considering hyphenation), so I doubt you will find ready-made solutions.

您想要做的只有在您使用固定宽度字体显示结果时才有效。否则一行中的字符数将不相同。如果这对你没问题,我会说你的情况相当罕见(特别是考虑到连字符),所以我怀疑你会找到现成的解决方案。

回答by Tony Ennis

If you're trying to format some manner of documentation, there's also the old unix roff (or runoff) family of commands. You'd just have to insert formatting commands and let roff do the heavy lifting.

如果您尝试格式化某种形式的文档,还有旧的 unix roff(或 runoff)命令系列。您只需要插入格式化命令并让 roff 完成繁重的工作。

回答by Praveen

public static List<String> stringBreak(String string, int maxChar) {

    List<String> subLines = new ArrayList<String>();

    int length = string.length();
    int start = 0;
    int end = maxChar;
    if (length > maxChar) {

        int noOfLines = (length / maxChar) + 1;

        int endOfStr[] = new int[noOfLines];

        for (int f = 0; f < noOfLines - 1; f++) {

            int end1 = maxChar;

            endOfStr[f] = end;

            if (string.charAt(end - 1) != ' ') {

                if (string.charAt(end - 2) == ' ') {

                    subLines.add(string.substring(start, end - 1));
                    start = end - 1;
                    end = end - 1 + end1;

                } else if (string.charAt(end - 2) != ' '
                        && string.charAt(end) == ' ') {

                    subLines.add(string.substring(start, end));
                    start = end;
                    end = end + end1;

                } else if (string.charAt(end - 2) != ' ') {

                    subLines.add(string.substring(start, end) + "-");
                    start = end;
                    end = end + end1;

                } else if (string.charAt(end + 2) == ' ') {
                    System.out.println("m here ............");
                    int lastSpaceIndex = string.substring(start, end)
                            .lastIndexOf("");
                    subLines.add(string.substring(start, lastSpaceIndex));

                    start = lastSpaceIndex;
                    end = lastSpaceIndex + end1;
                }

            } else {

                subLines.add(string.substring(start, end));
                start = end;
                end = end + end1;
            }

        }

        subLines.add(string.substring(endOfStr[noOfLines - 2], length));

    }

    return subLines;
}

回答by Esko Piirainen

Here's my take

这是我的看法

private static final String LINEBREAK = "\n"; // or "\r\n";

public static String wrap(String string, int lineLength) {
    StringBuilder b = new StringBuilder();
    for (String line : string.split(Pattern.quote(LINEBREAK))) {
        b.append(wrapLine(line, lineLength));
    }
    return b.toString();
}

private static String wrapLine(String line, int lineLength) {
    if (line.length() == 0) return LINEBREAK;
    if (line.length() <= lineLength) return line + LINEBREAK;
    String[] words = line.split(" ");
    StringBuilder allLines = new StringBuilder();
    StringBuilder trimmedLine = new StringBuilder();
    for (String word : words) {
        if (trimmedLine.length() + 1 + word.length() <= lineLength) {
            trimmedLine.append(word).append(" ");
        } else {
            allLines.append(trimmedLine).append(LINEBREAK);
            trimmedLine = new StringBuilder();
            trimmedLine.append(word).append(" ");
        }
    }
    if (trimmedLine.length() > 0) {
        allLines.append(trimmedLine);
    }
    allLines.append(linebreak);
    return allLines.toString();
}

(This solution strips two spaces to one space (so same fault that @jett has with Apache commons WordUtils)).

(此解决方案将两个空格剥离为一个空格(@jett 对 Apache commons WordUtils 的错误也是如此))。

回答by Dave Moten

Use the word-wraplibrary (available on Maven Central).

使用自动换行库(可在 Maven Central 上获得)。

Here's one way to use it:

这是使用它的一种方法:

String text = "hello how are you going?";
String wrapped = 
  WordWrap.from(text)
    .maxWidth(10)
    .insertHyphens(true) // true is the default
    .wrap();

Output is:

输出是:

hi there
how are
you going?

The library conserves leading spaces on lines which is one complaint about the behaviour of the Apache commons-langoffering. You can also specify the stringWidthfunction to get pixel-accurate results when rendering the text.

该库在行上保留了前导空格,这是对 Apache commons-lang产品行为的一种抱怨。您还可以指定stringWidth函数以在渲染文本时获得像素精确的结果。

The library has decent unit test coverage (something to bear in mind when you consider copy and paste of code chunks from the web!).

该库具有不错的单元测试覆盖率(当您考虑从网络复制和粘贴代码块时,请记住这一点!)。

The Maven dependency is:

Maven 依赖项是:

<dependency>
  <groupId>com.github.davidmoten</groupId>
  <artifactId>word-wrap</artifactId>
  <version>0.1.1</version>
</dependency>

Be sure to check for a later version.

请务必检查更高版本。