在 Java 中,String 的格式化输出常见有 3 种方式,下面按使用频率从高到低说明,并附示例。
String.format(最常用)String name = "Tom";
int age = 18;
String s = String.format("姓名:%s,年龄:%d", name, age);
System.out.println(s);
输出:
姓名:Tom,年龄:18
| 格式符 | 说明 |
|---|---|
%s |
字符串 |
%d |
整数 |
%f |
浮点数 |
%.2f |
保留2位小数 |
%n |
换行 |
System.out.printfSystem.out.printf("姓名:%s,年龄:%d%n", "Tom", 18);
效果和 String.format 类似,但直接输出。
MessageFormat(适合国际化)import java.text.MessageFormat;
String msg = MessageFormat.format("姓名:{0},年龄:{1}", "Tom", 18);
System.out.println(msg);
double price = 9.8765;
System.out.println(String.format("价格:%.2f", price));
System.out.println(String.format("%05d", 42)); // 00042
System.out.println(String.format("%-10s|", "name"));
System.out.println(String.format("%10s|", "name"));
String.formatprintfMessageFormat如果你有具体格式需求(如日期、金额、表格对齐),可以告诉我,我可以直接帮你写代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。