温馨提示×

Java中动态替换字符串模板的方法

小樊
99
2024-06-13 14:31:38
栏目: 编程语言

在Java中动态替换字符串模板的方法有多种,下面介绍两种常用的方法:

  1. 使用String.format()方法:
String template = "Hello, %s! Today is %s.";
String name = "Alice";
String date = "Monday";
String result = String.format(template, name, date);
System.out.println(result); // Output: Hello, Alice! Today is Monday.
  1. 使用String.replace()方法:
String template = "Hello, {name}! Today is {date}.";
String result = template.replace("{name}", "Alice").replace("{date}", "Monday");
System.out.println(result); // Output: Hello, Alice! Today is Monday.

这两种方法都可以实现动态替换字符串模板的功能,选择合适的方法取决于具体的需求和场景。

0