15

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

4

2 回答 2

44

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


作为一个简单的选项,您可以使用String.replaceAll()如下:

String output = <your string here>
String indented = output.replaceAll("(?m)^", "\t");

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

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

例如,以下代码:

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

产生这个输出:

	富
	酒吧
	巴兹
于 2013-04-08T21:11:38.677 回答
5

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

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)
于 2018-09-21T09:33:51.980 回答