3

I'm writing a simple diary console program. Can't really figure out what the easiest way to break up text input from the user. I take in a diary note in a string and then I want to be able to print that string to the console, but unformatted it of course just shows the string in one long line across the terminal making it terribly unfriendly to read. How would I show the string with a new line for every x characters or so? All I can find about text formatting is System.out.printf() but that just has a minimum amount of characters to be printed.

2
  • If you want to hard wrap a String you will need to insert linebreaks manually. You can System.out.print individual words and could the number of characters then insert the linebreak when a threshold is reached. Commented Oct 17, 2013 at 11:34
  • You could use String.split(" ") to split it into words at first. Commented Oct 17, 2013 at 11:34

4 Answers 4

7

I would recommend to use some external libraries to do, like Apache commons:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

and using

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#wrap(java.lang.String, int)

static final int FIXED_WIDTH = 80;

String myLongString = "..."; // very long string
String myWrappedString = WordUtils.wrap(myLongString,FIXED_WIDTH);

This will wrap your String, respecting spaces ' ', with a fixed width

WITHOUT EXTERNAL LIBRARIES

You will have to implement it:

BTW: I dont have a compiler of java here to test it, so dont rage if it does not compile directly.

private final static int MAX_WIDTH = 80;

public String wrap(String longString) {
    String[] splittedString = longString.split(" ");
    String resultString = "";
    String lineString = "";

    for (int i = 0; i < splittedString.length; i++) {
        if (lineString.isEmpty()) {
            lineString += splittedString[i];
        } else if (lineString.length() + splittedString[i].length() < MAX_WIDTH) {
            lineString += splittedString[i];
        } else {
            resultString += lineString + "\n";
            lineString = "";
        }
    }

    if(!lineString.isEmpty()){
            resultString += lineString + "\n";
    }

    return resultString;
}
Sign up to request clarification or add additional context in comments.

1 Comment

String has a length() not a size().
4

If you can use apache common lang library, you can use WordUtils class(org.apache.commons.lang.WordUtils). If you ex:

System.out.println("\nWrap length of 20, \\n newline, don't wrap long words:\n" + WordUtils.wrap(str2, 20, "\n", false)); [Source here][1]

If you can't you can use this function available in programmerscookbook blog. code to do custom wrapping of text

static String [] wrapText (String text, int len)
{
  // return empty array for null text
 if (text == null)
   return new String [] {};

 // return text if len is zero or less
 if (len <= 0)
   return new String [] {text};

 // return text if less than length
  if (text.length() <= len)
   return new String [] {text};

  char [] chars = text.toCharArray();
  Vector lines = new Vector();
  StringBuffer line = new StringBuffer();
  StringBuffer word = new StringBuffer();

  for (int i = 0; i < chars.length; i++) {
      word.append(chars[i]);

      if (chars[i] == ' ') {
        if ((line.length() + word.length()) > len) {
          lines.add(line.toString());
          line.delete(0, line.length());
        }

        line.append(word);
        word.delete(0, word.length());
      }
  }

 // handle any extra chars in current word
 if (word.length() > 0) {
   if ((line.length() + word.length()) > len) {
     lines.add(line.toString());
     line.delete(0, line.length());
  }
  line.append(word);
 }

// handle extra line
if (line.length() > 0) {
  lines.add(line.toString());
}

String [] ret = new String[lines.size()];
int c = 0; // counter
for (Enumeration e = lines.elements(); e.hasMoreElements(); c++) {
   ret[c] = (String) e.nextElement();
}

return ret;
}

This will return a string array, use a for loop to print.

Comments

0

You could use the Java java.util.StringTokenizer to split up the words by space character and in an loop you could then add a "\n" after your favorite number of words per line.

That's not per character but maybe it is not so readable to split words anywhere because of the number of characters where reached.

5 Comments

yes. this is probably be the more recommended solution by using String.split(..).
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
@DreadPirateShawn In my opinion from the months I've spent on this site this is sufficient for an answer.
@hexafraction -- No offense intended. This answer was automatically flagged by StackOverflow for moderation review, and the comment was auto-generated by the same. Given that both of the other answers provided code solutions, this answer seemed under-clarified by comparison. That being said, thanks for voicing your concern! Not all moderation decisions are perfect, and counterpoints are always appreciated.
@DreadPirateShawn Thanks for understanding. This is my second day with access to handling flags so I'm still getting used to the more formal policies.
0

You can use the following codes instead.

String separator = System.getProperty("line.separator");
String str = String.format("My line contains a %s break line", NEW_LINE);
System.out.println(str)

You can refer to this link. Java multiline string

1 Comment

Two questions, why bother declaring the separator variable if you never use it and where is NEW_LINE declared (unless that's a Java constant)? Also, if you didn't know, you can just use %n to format a newline character which is correct for the system.

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.