在 Java 中,可以通过多种方式替换字符串中的占位符内容。以下是几种常见的方法:
方法 1:使用 String.format
String.format
是一种简单且常用的方法,适用于格式化字符串并替换占位符。
public class Main {
public static void main(String[] args) {
String template = "Hello, %s! Welcome to %s.";
String result = String.format(template, "Alice", "Java World");
System.out.println(result); // 输出: Hello, Alice! Welcome to Java World.
}
}
占位符说明:
%s
表示字符串。%d
表示整数。%f
表示浮点数。
方法 2:使用 MessageFormat
MessageFormat
是 Java 提供的另一种格式化工具,支持更复杂的占位符。
import java.text.MessageFormat;
public class Main {
public static void main(String[] args) {
String template = "Hello, {0}! Welcome to {1}.";
String result = MessageFormat.format(template, "Alice", "Java World");
System.out.println(result); // 输出: Hello, Alice! Welcome to Java World.
}
}
特点:
- 占位符使用
{数字}
的形式。 - 支持更多复杂格式,如日期、数字等。
方法 3:使用 String.replace
或 String.replaceAll
如果占位符是固定的字符串,可以直接使用 replace
或 replaceAll
方法。
public class Main {
public static void main(String[] args) {
String template = "Hello, ${name}! Welcome to ${place}.";
String result = template.replace("${name}", "Alice").replace("${place}", "Java World");
System.out.println(result); // 输出: Hello, Alice! Welcome to Java World.
}
}
注意:
replace
替换单个字符或字符串。replaceAll
使用正则表达式进行替换。
方法 4:使用 StringBuilder
动态拼接
如果需要动态替换多个占位符,可以使用 StringBuilder
。
public class Main {
public static void main(String[] args) {
String template = "Hello, ${name}! Welcome to ${place}.";
String name = "Alice";
String place = "Java World";
StringBuilder sb = new StringBuilder(template);
int index;
while ((index = sb.indexOf("${")) != -1) {
int endIndex = sb.indexOf("}", index);
String placeholder = sb.substring(index, endIndex + 1);
String value = getValue(placeholder); // 自定义方法获取值
sb.replace(index, endIndex + 1, value);
}
System.out.println(sb.toString()); // 输出: Hello, Alice! Welcome to Java World.
}
private static String getValue(String placeholder) {
switch (placeholder) {
case "${name}":
return "Alice";
case "${place}":
return "Java World";
default:
return "";
}
}
}
方法 5:使用第三方库(如 Apache Commons Text)
Apache Commons Text 提供了 StringSubstitutor
类,用于替换占位符。
Maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
代码示例:
import org.apache.commons.text.StringSubstitutor;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String template = "Hello, ${name}! Welcome to ${place}.";
Map<String, String> values = new HashMap<>();
values.put("name", "Alice");
values.put("place", "Java World");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace(template);
System.out.println(result); // 输出: Hello, Alice! Welcome to Java World.
}
}
总结
- 简单场景:使用
String.format
或MessageFormat
。 - 固定占位符:使用
String.replace
。 - 动态场景:使用
StringBuilder
或第三方库(如 Apache Commons Text)。 - 复杂需求:推荐使用
StringSubstitutor
,功能强大且易于扩展。