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.

Community
  • 1
  • 1
mistysch
  • 77
  • 1
  • 6
  • 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. – Boris the Spider Oct 17 '13 at 11:34
  • You could use String.split(" ") to split it into words at first. – Kayaman Oct 17 '13 at 11:34

4 Answers4

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;
}
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
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.

Buddha
  • 4,339
  • 2
  • 27
  • 51
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.

BuddhaAir
  • 1
  • 2
  • yes. this is probably be the more recommended solution by using String.split(..). – BuddhaAir Oct 17 '13 at 11:47
  • 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](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – DreadPirateShawn Oct 17 '13 at 16:23
  • @DreadPirateShawn In my opinion from the months I've spent on this site this is sufficient for an answer. – nanofarad Oct 17 '13 at 23:30
  • 1
    @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 Oct 18 '13 at 05:00
  • @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. – nanofarad Oct 18 '13 at 10:19
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

Community
  • 1
  • 1
winningsix
  • 101
  • 4
  • 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. – Spencer D Mar 28 '15 at 01:57