Search code examples
javastringbuilder

How can I remove the last "new line" from the StringBuilder?


I have a set with hosts and a map with keys. I want to give out all with a StringBuilder. I tried this and more but didn't succeed.

StringBuilder sb=new StringBuilder();
    for(Map.Entry<String, String> entry:host.keys.entrySet()){
        if(this.keys.containsKey(entry.getKey())){
            if(entry.getValue().equals(this.keys.get(entry.getKey()))){

                String separator="";
                sb.append(separator);
                sb.append(host.hostnamen);
                sb.append(" ");
                sb.append(entry.getKey());
                sb.append(" ");
                sb.append(entry.getValue());
                separator="\n";

            }
        }
    }
    System.out.println(sb.toString());

This is what I get.

[klon] ssh-rsa AAAABXYZ[klon] ssh-xxx abc[klon] ssh-yyy def

This is what I expected...

[klon] ssh-rsa AAAABXYZ
[klon] ssh-xxx abc
[klon] ssh-yyy def

Solution

  • Your problem is, that in the loop you are overwriting the separator again with a "" at the next loop. I changed it here by moving the separator to the beginning. Then, upon the next cycle, it will still contain the newline sign.

    StringBuilder sb=new StringBuilder();
    String separator="";
    for(Map.Entry<String, String> entry:host.keys.entrySet()){
        if(this.keys.containsKey(entry.getKey())){
            if(entry.getValue().equals(this.keys.get(entry.getKey()))){
                sb.append(separator);
                sb.append(host.hostnamen);
                sb.append(" ");
                sb.append(entry.getKey());
                sb.append(" ");
                sb.append(entry.getValue());
                separator="\n";
    
            }
        }
    }
    System.out.println(sb.toString());