2

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

Community
  • 1
  • 1
Matteo
  • 7,924
  • 24
  • 84
  • 129
  • can't you put '\n' in your string_variable_containing_post? – soulcheck Dec 02 '11 at 11:31
  • 1
    See accepted answer to this question: http://stackoverflow.com/questions/891969/how-do-i-optimize-this-method-for-breaking-a-string-in-chunks – anubhava Dec 02 '11 at 11:32
  • @shoulcheck fact is that I directly store the content of post in the string, with no processing of it.To insert '\n' I would need to access it, and modify it's content, which is not what I want to do. – Matteo Dec 02 '11 at 11:35
  • @anubhava nice one, I'm checking it.. – Matteo Dec 02 '11 at 11:38

2 Answers2

1

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

Zohaib
  • 7,026
  • 3
  • 26
  • 35
0

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);
 }
soulcheck
  • 36,297
  • 6
  • 91
  • 90