文章目录
在Java中,有多种方法可以用来替换字符串中的占位符。以下是几种常用的技术:
1. 使用 String.format()
String.format()
是一个非常强大的工具,它允许你使用类似于C语言的格式化语法来构建字符串。它可以自动替换指定的占位符。
String template = "Hello, %s!";
String result = String.format(template, "World");
System.out.println(result); // 输出: Hello, World!
2. 使用 MessageFormat
MessageFormat
类提供了更复杂的占位符替换功能,包括国际化支持。
String template = "Hello, {0}!";
MessageFormat formatter = new MessageFormat(template);
String result = formatter.format(new Object[]{
"World"});
System.out.println