Java String替换不起作用

Vil*_*ius 16 java string replace

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());
}
Run Code Online (Sandbox Code Playgroud)

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

Yis*_*hai 50

String是不可变的,这意味着html引用不会更改,而replace方法返回一个您必须分配的新String对象.

html = html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
Run Code Online (Sandbox Code Playgroud)


MRA*_*RAB 6

replace方法返回其丢弃的结果.