在Java中将字符串附加到字符串中

时间:2014-10-18 03:22:05

标签: java

我在Java中使用此代码,getter方法返回字符串:

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#有一个带有AppendFormat()方法的StringBuilder类,它允许我将格式化的字符串直接附加到StringBuilder实例,而不必进行连接。我没有在Java StringBuider类中看到AppendFormat()方法。有没有更好的方法来做我想做的事情?

1 个答案:

答案 0 :(得分:0)

here看起来像Java Formatter类就是你想要的:

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