【最常用】两种java中的占位符的使用 第一种:使用%s占位,使用String.format转换 第二种:使用{1}占位,使用MessageFormat.format转换
https://blog.csdn.net/weixin_43899069/article/details/121164107
先介绍一下format是什么:
Java中允许我们对指定的对象进行某种格式化,从而得到我们想要的格式化样式。而format可以帮助我们从某种格式转化到我们想要的格式的一种工具。
第一种:使用%s占位,使用String.format转换
public class Test {
public static void main(String[] args) {
String url = "我叫%s,今年%s岁。";
String name = "小明";
String age = "28";
url = String.format(url,name,age);
System.out.println(url);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
控制台输出:
我叫小明,年28岁。
第二种:使用{1}占位,使用MessageFormat.format转换
public class Test {
public static void main(String[] args) {
String url02 = "我叫{0},今年{1}岁。";
String name = "小明";
String age = "28";
url02 = MessageFormat.format(url02,name,age);
System.out.println(url02);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
控制台同样输出:
我叫小明,今年28岁。
发现了一个很精华的博客,关于format的详细解析见这里:https://www.jianshu.com/p/c8f16cab35e1#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)