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

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

问题描述

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?

推荐答案

String 是不可变的,这意味着 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字符串替换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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