gpt4 book ai didi

java - String的replace()方法的问题

转载 作者:行者123 更新时间:2023-12-01 07:58:04 24 4
gpt4 key购买 nike

我试图替换以 $ 开头的字符串部分(我手动使用字符串中的参数),但由于某种原因它失败了。这是我所拥有的:

 public void sendNotificationOfAcceptedMeeting(String candidateName, DateTime dateTime) {
Map<String,String> params = new HashMap<String,String>();
params.put("date", dateTime.toString(DATETIME_FORMAT));
params.put("candidate", candidateName);
sendEmailWithTemplate(TEMPLATE_ALL_ACCEPTED, params);
}

然后:

private void sendEmailWithTemplate(String templateName, Map<String, String> params) {
EmailTemplate template = emailTemplateDao.getEmailTemplate(templateName);
String subject = applyTemplateParameters(template.getSubject(), params);
String body = applyTemplateParameters(template.getTetxBody(), params);
sendEmail(subject, body);
}

最后:

private String applyTemplateParameters(String templateText, Map<String, String> params) {
String toReturn = templateText;
if (params != null) {
System.out.println("map size: " + params.size());
for (Entry<String, String> entry : params.entrySet()) {
System.out.println("********************");
System.out.println(toReturn + " ***BEFORE");
toReturn.replace("$" + entry.getKey(), entry.getValue());
System.out.println("$" + entry.getKey() + " ***KEY");
System.out.println(entry.getValue() + " ***VALUE");
System.out.println(toReturn + " AFTER");
}
}
return toReturn;
}

正如您可能想到的,第二个方法使用我想要修改的字符串以及参数及其值的映射来调用第三个方法。第二种方法将 template String 的 vlue 设置为:

    The meeting request at $date with $candidate was accepted by all interviewers.

但是第三种方法中的系统输出打印:

    map size: 2
********************
The meeting request at $date with $candidate was
accepted by all interviewers. ***BEFORE
$candidate ***KEY
Acceeedsasd Stetfghfghasd ***VALUE
The meeting request at $date with $candidate was
accepted by all interviewers. AFTER
********************
The meeting request at $date with $candidate was
accepted by all interviewers. ***BEFORE
$date ***KEY
27/12/2014 8:00 ***VALUE
The meeting request at $date with $candidate was
accepted by all interviewers. AFTER

清楚地表明它不会替换参数...我认为也许 $ 会破坏它(正则表达式),但是 replace()replaceAll( ) 采用字符串 - 而不是正则表达式。我没有主意,感谢任何帮助。

最佳答案

你必须这样做:

 toReturn = toReturn.replace("$" + entry.getKey(), entry.getValue());

然后打印 toReturn 的值

关于java - String的replace()方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27601535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com