Java小抄|Java中字符串占位符替换的多种实现方法
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
public class StringReplaceExample {
public static void main(String[] args) {
String template = "我的名字是%s,今年%d岁。";
// 使用String.format
String formattedString = String.format(template, "小抄", 18);
System.out.println(formattedString); // 输出: 我的名字是小抄,今年18岁。
// 使用MessageFormat.format
String formattedMessage = MessageFormat.format(template, "小抄", 18);
System.out.println(formattedMessage); // 输出: 我的名字是小抄,今年18岁。
// 使用StringBuilder或StringBuffer的append方法
StringBuilder sb = new StringBuilder();
sb.append("我的名字是");
sb.append("小抄");
sb.append(",今年");
sb.append(18);
sb.append("岁。");
System.out.println(sb.toString()); // 输出: 我的名字是小抄,今年18岁。
// 使用java.util.Formatter
Formatter formatter = new Formatter();
String formattedByFormatter = formatter.format(template, "小抄", 18).toString();
System.out.println(formattedByFormatter); // 输出: 我的名字是小抄,今年18岁。
formatter.close(); // 使用完Formatter后应关闭,避免资源泄露
}
}
这段代码展示了在Java中使用不同方法来进行字符串替换的例子。包括使用String.format
、MessageFormat.format
、字符串拼接(使用StringBuilder
或StringBuffer
)以及java.util.Formatter
。每种方法都有其适用的场景,开发者可以根据具体需求选择合适的方法。
评论已关闭