Java 有没有一种简单的方法可以将多行文本连接成一个字符串而无需不断添加换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2509170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:37:44  来源:igfitidea点击:

Is there an easy way to concatenate several lines of text into a string without constantly appending a newline?

javastringappendconcatenation

提问by Marshmellow1328

So I essentially need to do this:

所以我基本上需要这样做:

String text = "line1\n";
text += "line2\n";
text += "line3\n";
useString( text );

There is more involved, but that's the basic idea. Is there anything out there that might let me do something more along the lines of this though?

有更多的参与,但这是基本的想法。有什么东西可以让我做更多类似的事情吗?

DesiredStringThinger text = new DesiredStringThinger();
text.append( "line1" );
text.append( "line2" );
text.append( "line3" );
useString( text.toString() );

Obviously, it does not need to work exactly like that, but I think I get the basic point across. There is always the option of writing a loop which processes the text myself, but it would be nice if there is a standard Java class out there that already does something like this rather than me needing to carry a class around between applications just so I can do something so trivial.

显然,它不需要完全那样工作,但我想我明白了基本点。总是可以选择编写一个自己处理文本的循环,但是如果有一个标准的 Java 类已经在做这样的事情,而不是我需要在应用程序之间携带一个类,这样我就可以了做些微不足道的事。

Thanks!

谢谢!

采纳答案by Joachim Sauer

You can use a StringWriterwrapped in a PrintWriter:

您可以使用StringWriter包装在 a 中PrintWriter

StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter, true);
writer.println("line1");
writer.println("line2");
writer.println("line3");
useString(stringWriter.toString());

回答by missingfaktor

AFAIK there's no library class that allows you to do so.

AFAIK 没有允许您这样做的库类。

The following does the work though:

下面的工作虽然:

class DesiredStringThinger {
  StringBuilder text = new StringBuilder();

  public void append(String s) { text.append(s).append("\n"); }

  @Override
  public String toString() { return text.toString(); }
}

回答by Roman

public String createString () {
   StringBuilder sb = new StringBuilder ();
   String txt = appendLine("firstline", sb).appendLine("2ndLine", sb).toString();
}

private StringBuilder appendLine (String line, StringBuilder sb) {
   String lsp = System.getProperty("line.separator");
   return sb.append (line).append (lsp);
}

回答by rayd09

You can use a StringBuffer

您可以使用 StringBuffer

StringBuffer text = new StringBuffer();
text.append("line1");  
text.append("line2");  
...  
useString(text.toString());   

This will not append the new line character, but you can certainly append that as well for each line.

这不会附加新行字符,但您当然可以为每一行附加该字符。

回答by Tom Hawtin - tackline

Perhaps the lowest impact method is to add a static method to append with a new line to a StringBuilder.

也许影响最小的方法是添加一个静态方法以在StringBuilder.

 public static StringBuilder appendln(StringBuilder buff, String str) {
     return buff.append(str).append('\n');
 }

But @Joachim Sauerbeats me to my preferred solution. For more complex examples you might want to use your own Writerdecorator, as @Rahul G(only use private fields).

@Joachim Sauer击败了我的首选解决方案。对于更复杂的示例,您可能希望使用自己的Writer装饰器,如@Rahul G(仅使用私有字段)。

回答by Enno Shioji

If you are not crazy about performance, I think this is clean and neat.

如果您对性能不感冒,我认为这很干净整洁。

class DesiredStringThinger {
  StringBuilder sb = new StringBuilder();

  public void concat(String... s) { 
      for(String str : s){
         sb.append(s).append("\n");
      }
  }

  @Override
  public String toString() { 
      return sb.toString();
  }
}

回答by GandalfIX

You can use from Apache Commonsthe StringUtils.join helper. Which allows to build a String from a list. You can add the 'delimiter' character/string.

您可以从Apache Commons使用 StringUtils.join 帮助程序。这允许从列表构建一个字符串。您可以添加“分隔符”字符/字符串。

回答by Carl

If you are willing to use external libraries, check out the Joinerin Guava.

如果您愿意使用外部库,请查看Guava 中的Joiner

Your code would go to something like

你的代码会变成类似的东西

String result = Joiner.on("\n").join(parts);

where partsis an Iterable<String>.

哪里partsIterable<String>.

回答by Joel Richard Koett

Here's a Java 8 solution using a stream:

这是使用流的 Java 8 解决方案:

public class DesiredStringThinger {

    private List<String> items = new ArrayList<>();

    public void append(String s) {
        items.add(s);
    }

    @Override
    public String toString() {
        return items.stream().collect(Collectors.joining("\n", "", "\n"));
    }

}