我有一个字符串如下
Hey {1}, you are {2}.
Run Code Online (Sandbox Code Playgroud)
这里1和2是关键将动态增加其价值.
现在我需要替换{1}为1表示的值,然后我需要替换上面句子{2}中2表示的值.
我该怎么做?
我知道字符串的分割功能是什么,我非常清楚,通过该功能,我可以做我想做的事,但我正在寻找更好的东西.
注意:我事先并不知道这些键是什么.我也需要检索密钥.然后根据键我需要替换字符串中的值.
感谢/sf/users/38375781/这一个.. :).你可以这样做:
public static void main(String[] args) {
String s = "Hey {1}, you are {2}.";
HashMap<Integer, String> hm = new HashMap();
hm.put(1, "one");
hm.put(2, "two");
Pattern p = Pattern.compile("(\\{\\d+\\})");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
String val1 = m.group().replace("{", "").replace("}", "");
System.out.println(val1);
s = (s.replace(m.group(), hm.get(Integer.parseInt(val1))));
System.out.println(s);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Hey one, you are two.
Run Code Online (Sandbox Code Playgroud)
尝试使用String.format():
String x = String.format("Hi %s, you are %s\n", str1, str2);
Run Code Online (Sandbox Code Playgroud)
如果你已经有一个字符串"Hey {1}, you are {2}.",你可以使用正则表达式替换{1}和{2}使用%s。
String template = "Hey {1}, you are {2}.";
String x = String.format(template.replaceAll("\\{\\d\\}", "%s"), "Name", "Surname");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11801 次 |
| 最近记录: |