简体   繁体   English

在Java中格式化控制台的文本输出

[英]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? 如何为每个x字符左右显示一个新行的字符串? All I can find about text formatting is System.out.printf() but that just has a minimum amount of characters to be printed. 我能找到的关于文本格式的所有内容都是System.out.printf(),但是只需要打印最少量的字符。

I would recommend to use some external libraries to do, like Apache commons: 我建议使用一些外部库来做,比如Apache commons:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html 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) 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 这将使用固定宽度包装您的String,尊重空格''

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. BTW:我这里没有java的编译器来测试它,所以如果不直接编译就不要愤怒。

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). 如果可以使用apache常见的lang库,则可以使用WordUtils类(org.apache.commons.lang.WordUtils)。 If you ex: 如果你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. 如果你不能,你可以在programmerscookbook博客中使用这个功能。 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. 这将返回一个字符串数组,使用for循环进行打印。

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. 您可以使用Java java.util.StringTokenizer按空格字符拆分单词,然后在循环中,您可以在每行最喜欢的单词数之后添加“\\ n”。

That's not per character but maybe it is not so readable to split words anywhere because of the number of characters where reached. 这不是每个字符,但由于到达的字符数,可能在任何地方拆分单词都不太可读。

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 Java多行字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM