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

4
  • can't you put '\n' in your string_variable_containing_post? Commented Dec 2, 2011 at 11:31
  • 1
    See accepted answer to this question: stackoverflow.com/questions/891969/… Commented Dec 2, 2011 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. Commented Dec 2, 2011 at 11:35
  • @anubhava nice one, I'm checking it.. Commented Dec 2, 2011 at 11:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.