1

有没有办法对齐很长​​的文本?

例如此代码:

System.out.println("\tHi this is a very long string to test the automated newline but I want to have the newline to be tab indented too.");

而不是下面

    Hi this is a very long string to test the automated newline but I want to 
have the newline to be tab indented too.

我要这个

    Hi this is a very long string to test the automated newline but I want to 
    have the newline to be tab indented too.

所以,我希望换行符与第一句话对齐。是否存在任何库或默认的 String Java 方法?

4

5 回答 5

1

我不相信 JDK 中有内置的方法可以做到这一点。

我知道的最佳解决方案是使用Apache Commons LangWordUtils.wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords)的一部分。

此方法允许您指定要换行的列数以及换行符。您可以使用\n\t换行符来换行,然后按照您的要求使用制表符缩进下一行。

例子:

import org.apache.commons.lang3.text.WordUtils;

public class Demo
{
    public static void main(String[] args)
    {
        String longString = "\tThe quick brown fox jumps over the fence";
        System.out.println(WordUtils.wrap(longString, 10, "\n\t", false));
    }

} 

- 编辑 -

Commons Lang 库可能太大而无法包含在 Android 应用程序中。但是,源代码WordUtils.wrap(...)很容易获得,因此您始终可以创建自己的精简版WordUtils.

于 2013-09-11T04:12:32.037 回答
1

在打印语句中使用 ("\t" + "Hi, this is newline")

于 2013-09-11T03:38:57.883 回答
1

你能告诉我们你正在使用的代码吗?如果您希望它们都对齐和标签,您可能希望两行都出现 \t 。

于 2013-09-11T03:40:11.207 回答
1

简而言之,没有。控制台的宽度可能因执行而异,Java 根本不提供该信息。但是,您可以假设最小值为 80 个字符,然后手动将其换成 80 个字符。看到这个问题

于 2013-09-11T03:54:42.080 回答
0

没有直接的方法可以通过StringAPI 实现自动换行。你必须想出一个你自己的实用方法。这是一个简单的实现,它将String输入包装在指定的lineSize.

void printWordWrapped(String string, int lineSize) {
    int len = (len = string.length()) > lineSize ? lineSize : len;
    do {
        System.out.printf("\t%s\n", string.substring(0, len).trim());
        string = string.substring(len);
        len = (len = string.length()) > lineSize ? lineSize : len;
    } while (len > 0);
}

printWordWrapped("Hi this is a short string.", 30);
System.out.println();
printWordWrapped("Hi this is a very long string to test " +
                 "the automated newline but I want to have " + 
                 "the newline to be tab indented too.", 30);

输出

    Hi this is a short string.

    Hi this is a very long string
    to test the automated newline
    but I want to have the newline
    to be tab indented too.
于 2013-09-11T06:06:23.670 回答