简体   繁体   English

如何在多行输出Java中打印字符串

[英]How to print a String in multiline Output Java

First of all I'd like to state that, despite the title, this question is not a duplicate of the one I found here: Java multiline string . 首先,我想说明一下,尽管有标题,但这个问题与我在这里发现的问题不是重复的: Java multiline string I read with attention all answers to that question and couldn't find a solution to my problem. 我仔细阅读了该问题的所有答案,但找不到解决我问题的方法。

The fundamental difference between my problem and the one of the other question is that I need to print in multiple lines a string of which I do not now in advance the length, so cannot define formatting as specified in those answers by dividing the string in chuncks. 我的问题和另一个问题之间的根本区别是,我需要多行打印一个字符串,但现在我不预先指定其长度,因此无法通过将字符串分成多个小块来定义这些答案中指定的格式。

I wrote a Java application that prints on console posts downloaded from web forums. 我编写了一个Java应用程序,该应用程序可以在从Web论坛下载的控制台帖子上进行打印。 The problem I'm facing is that since post content is saved in a string, when I print it on screen with 我面临的问题是,由于帖子内容保存在字符串中,因此当我使用

System.out.println(string_variable_containing_post)

it will go to new line only at the very end of the string. 它只会在字符串的末尾转到新行。

This is very uncomfortable. 这是非常不舒服的。

I would like to know if there is a way of specifying a maximum number of bytes after which insert a new line automatically. 我想知道是否有一种指定最大字节数的方法,之后自动插入新行。

Thanks in advance, 提前致谢,

Matteo 马特奥

if length of String abc is 200 and I want 100 characters on one line, then one dirty approach might be 如果字符串abc的长度是200,而我想在一行上输入100个字符,那么一种肮脏的方法可能是

System.out.println(abc.substring(0,100) + "\n" + abc.substring(100,200));

You can do this in a loop to append \\n in originial abc 您可以循环执行此操作以在原始abc中附加\\ n

You can use Guava's Splitter 您可以使用番石榴的分离器

 Iterable<String> lines = Splitter.fixedLength(desiredLineLength).split(string_variable_containing_post);
 for (String line : lines) {
      System.out.println(line);
 }

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

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