Java String替换不起作用 [英] Java String replace not working

查看:182
本文介绍了Java String替换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String delimiter = "\\*\\*";
String html = "<html><head></head><body>**USERNAME** AND **PASSWORD**</body></html>";
Map<String, String> mp = new HashMap<String, String>();
mp.put("USERNAME", "User A");
mp.put("PASSWORD", "B");
for (Entry<String, String> entry : mp.entrySet()) {
  html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
}

通常应该替换这两个字符串,但事实并非如此。有没有人有想法?

That should usually replace those both strings, but it does not. Does anyone has an idea?

推荐答案

字符串是不可变的,这意味着html引用不会改变,而是替换方法返回一个你必须分配的新String对象。

String is immutable, which means that the html reference doesn't change, rather the replace method returns a new String object that you have to assign.

html = html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());

这篇关于Java String替换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆