Format text output for console in Java

谁说我不能喝 提交于 2019-12-06 00:17:05

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

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.

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.

winningsix

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!