如何在java中缩进正在写入控制台的多行段落

2022-09-03 08:44:47

任何人都可以建议一种方法将多行字符串写入系统控制台并缩进该文本块吗?我正在寻找一些相对轻量级的东西,因为它仅用于显示命令行程序的帮助。


答案 1

注意:下文所述的方法不符合问题评论中@BillMan所述的最新要求。这不会自动换行超过控制台行长度的行 - 仅当换行不是问题时才使用此方法。


作为一个简单的选项,您可以使用 String.replaceAll(),如下所示:
String output = <your string here>
String indented = output.replaceAll("(?m)^", "\t");

如果您不熟悉Java正则表达式,它的工作原理如下:

  • (?m)启用多行模式。这意味着 IN 中的每一行都是单独考虑的,而不是被视为一行(这是默认值)。outputoutput
  • ^是与每行开头匹配的正则表达式。
  • \t使前面的正则表达式的每个匹配项(即每行的开头)替换为制表符。

例如,以下代码:

String output = "foo\nbar\nbaz\n"
String indented = output.replaceAll("(?m)^", "\t");
System.out.println(indented);

生成以下输出:

	foo
	bar
	baz

答案 2

通过 JDK/12 早期访问版本,现在可以利用 String 类的 API,该 API 目前在预览功能下可用,可以用作:indent

String indentedBody =
`<html>
   <body>
       <p>Hello World - Indented.</p>
   </body>
</html>`.indent(4);

并且上述代码的输出将是

    <html>
       <body>
           <p>Hello World - Indented.</p>
       </body>
    </html>

API 的当前文档规范还如下所示:

/**
 * Adjusts the indentation of each line of this string based on the value of
 * {@code n}, and normalizes line termination characters.
 * <p>
 * This string is conceptually separated into lines using
 * {@link String#lines()}. Each line is then adjusted as described below
 * and then suffixed with a line feed {@code "\n"} (U+000A). The resulting
 * lines are then concatenated and returned.
 * <p>
 * If {@code n > 0} then {@code n} spaces (U+0020) are inserted at the
 * beginning of each line. {@link String#isBlank() Blank lines} are
 * unaffected.
 * <p>
 * If {@code n < 0} then up to {@code n}
 * {@link Character#isWhitespace(int) white space characters} are removed
 * from the beginning of each line. If a given line does not contain
 * sufficient white space then all leading
 * {@link Character#isWhitespace(int) white space characters} are removed.
 * Each white space character is treated as a single character. In
 * particular, the tab character {@code "\t"} (U+0009) is considered a
 * single character; it is not expanded.
 * <p>
 * If {@code n == 0} then the line remains unchanged. However, line
 * terminators are still normalized.
 * <p>
 *
 * @param n  number of leading
 *           {@link Character#isWhitespace(int) white space characters}
 *           to add or remove
 *
 * @return string with indentation adjusted and line endings normalized
 *
 * @see String#lines()
 * @see String#isBlank()
 * @see Character#isWhitespace(int)
 *
 * @since 12
 */
public String indent(int n)

推荐