简体   繁体   中英

Appending Formats to Strings in Java

I have this code in Java, the getter methods return Strings:

String stringbuilder="";
stringbuilder = String.format("%d/%d\n", this.getSlotNum(), this.getPortNum());
stringbuilder = stringbuilder+String.format(" " + this.getPortSpeed() +"\n");
stringbuilder = stringbuilder+String.format("%d\n", this.getPortMode());

C# has a StringBuilder Class with an AppendFormat() method that lets me append a formatted string directly to the StringBuilder instance without having to do the concatenation. I don't see an AppendFormat() method in thethn Java StringBuider class. Is there a better way to do what I am trying to do?

From here looks like the Java Formatter class is what you want:

Formatter formatter = new Formatter();
formatter.format("Hello, world\n");
if (name != null) {
    formatter.format("My name is %s\n", name);
} else {
    formatter.format("Please email me at %s\n", email);
}
doUse(formatter.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