mistysch
mistysch

Reputation: 77

Format text output for console in Java

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.

Upvotes: 3

Views: 9668

Answers (4)

winningsix
winningsix

Reputation: 111

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

Upvotes: 0

Buddha
Buddha

Reputation: 4476

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.

Upvotes: 4

RamonBoza
RamonBoza

Reputation: 9038

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

Upvotes: 7

BuddhaAir
BuddhaAir

Reputation: 1

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.

Upvotes: 0

Related Questions