Can anyone suggest a method for writing a mutli-line String to a system console and having that text block be indented? I'm looking for something relatively lightweight because it's only being used for displaying help for a command line program.
NOTE: The approach described below does not meet the updated requirements described by @BillMan in the question's comments. This will not automatically wrap lines that are longer than the console line length - only use this approach if wrapping isn't an issue.
String output = <your string here> String indented = output.replaceAll("(?m)^", "\t");
If you're unfamiliar with Java regular expressions, it works as follows:
(?m)enables multiline mode. This means each line in
outputis considered individually, instead of treating
outputas a single line (which is the default).
^is a regex matching the start of each line.
\tcauses each match of the preceding regex (i.e. the start of each line) to be replaced by a tab character.
As an example, the following code:
String output = "foo\nbar\nbaz\n" String indented = output.replaceAll("(?m)^", "\t"); System.out.println(indented);
Produces this output:
foo bar baz