Reputation: 8124
First of all I'd like to state that, despite the title, this question is not a duplicate of the one I found here: Java multiline string. I read with attention all answers to that question and couldn't find a solution to my problem.
The fundamental difference between my problem and the one of the other question is that I need to print in multiple lines a string of which I do not now in advance the length, so cannot define formatting as specified in those answers by dividing the string in chuncks.
I wrote a Java application that prints on console posts downloaded from web forums. The problem I'm facing is that since post content is saved in a string, when I print it on screen with
System.out.println(string_variable_containing_post)
it will go to new line only at the very end of the string.
This is very uncomfortable.
I would like to know if there is a way of specifying a maximum number of bytes after which insert a new line automatically.
Thanks in advance,
Matteo
Upvotes: 2
Views: 2895
Reputation: 36767
You can use Guava's Splitter
Iterable<String> lines = Splitter.fixedLength(desiredLineLength).split(string_variable_containing_post);
for (String line : lines) {
System.out.println(line);
}
Upvotes: 0
Reputation: 7116
if length of String abc is 200 and I want 100 characters on one line, then one dirty approach might be
System.out.println(abc.substring(0,100) + "\n" + abc.substring(100,200));
You can do this in a loop to append \n in originial abc
Upvotes: 1