简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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