开发者

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

开发者 https://www.devze.com 2022-12-24 04:50 出处:网络
So I essentially need to do this: String text = \"line1\\n\"; text += \"line2\\n\"; text += \"line3\\n\";

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 arou开发者_如何转开发nd between applications just so I can do something so trivial.

Thanks!


You can use a StringWriter wrapped in a PrintWriter:

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


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

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


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


Here's a Java 8 solution using a stream:

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

}


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


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

Your code would go to something like

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

where parts is an Iterable<String>.


Java SE 8

With Java SE 8, a couple of additional ways can be by:

  1. Using String#join
  2. Using Stream.

Demo:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String[] arr = { "line1", "line2", "line3" };

        // Using String#join
        System.out.println(String.join(System.lineSeparator(), arr));

        System.out.println();

        // Using Stream
        System.out.println(Arrays.stream(arr).collect(Collectors.joining(System.lineSeparator())));
    }
}

Output:

line1
line2
line3

line1
line2
line3


You can use a 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.


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

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

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


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


In java 8 you can do this

String[] lines = new String[]{"line1", "line2", "line3"};
String s = String.join("\n", lines);

docs here

0

精彩评论

暂无评论...
验证码 换一张
取 消