使用return string.format(...)在Java中格式化字符串

时间:2011-09-02 00:32:30

标签: java string format

说我想要返回这样的内容: “标题 bookTitle ,作者 bookAuthor :$ 费用

粗体是变量。 我无法弄清楚如何使用string.format(“%s ..,blah blah”)

返回此内容

3 个答案:

答案 0 :(得分:9)

String title = "bookTitle";
String author = "bookAuthor";
double cost = 100;
String text = String.format("Title %s, Author %s: $%.2f", title, author, cost);
System.out.println(text); // prints "Title bookTitle, Author bookAuthor: $100.00"
// or System.out.pritnf("Title %s, Author %s: $%.2f", title, author, cost);

答案 1 :(得分:4)

2个字符串和精度为2的浮点

String.format("Title %s, Author %s: $%f.2", bookTitle, bookAuthor, cost);

答案 2 :(得分:2)

String fs;
fs = String.format("Title %t, Author %a: $%c", bookTitle, bookAuthor, cost);
System.out.println(fs);

http://download.oracle.com/javase/tutorial/java/data/strings.html