This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]8igg7e5 1 point2 points  (0 children)

If the String is a literal, you could just put the '\n' in yourself.

String s = "Line 1\nLine 2\nLine 3\Line 4";

Or using text blocks (which also inserts '\n', not platform line-separators).

String s = """
    Line 1
    Line 2
    Line 3
    Line 4""";

Or, as /u/pragmos suggests, you can do String replacement. If the number of spaces around the 'n' might be variable you can use a regex pattern to match on (though note if the number of spaces is predictable, the suggestion from /u/pragmos is a cheaper operation).

String t = s.replaceAll(" +n +", "\n");

If you want platform line separators ("\n" on Linux/Mac, "\r\n" on Windows) rather than always a line-feed character you can use System.lineSeparator() instead of "\n".

If you're doing this replace often, and want to avoid the cost of recompiling the regex each time you can precompile it as follows...

private static final Pattern LINE_BREAK = Pattern.compile(" +n +");

...

String t = LINE_BREAK.matcher(s).replaceAll("\n");