[英]Why is my method using String.replace and a HashMap not replacing the strings?
[英]String.replace() is replacing one of two strings only
我有这行文字:
美国驻扎在越南南部的部队人数与驻扎在西德的部队人数相比。
我正在尝试做的是检查文本行中是否存在组合时可能有意义的任何单词。
例如:用正确的单词vietnam
替换viet nam
String 。
我写了这个 function:
private String correctLine(ArrayList<String> newWords, String line) {
line = line.toLowerCase();
String[] words = line.split(" ");
for (int i = 0; i < newWords.size(); i++) {
for (int j = 0; j < words.length; j++) {
if(newWords.get(i).toLowerCase().equals(words[j].concat((j + 1 == words.length)?"":words[j+1]))){
line = line.replace(words[j].toLowerCase(), newWords.get(i).toLowerCase());
line = line.replace(words[j+1].toLowerCase(), "");
}
}
}
return line;
}
这个 function 所做的是将在文本中替换的单词列表newWords
和 text line
的目标行。
问题:
当满足if
条件时:
vietnam
等于words[j]
(越南) & words[j+1]
(nam)
我更换了line
:
viet
替换为vietnam
。nam
替换为
.但所发生的只是其中一个被替换,而另一个被忽略。
如果我评论第一个replace
结果是:
number of troops the united states has stationed in south viet as compared with the number of troops it has stationed in west germany.
如果我评论第二个replace
结果是:
number of troops the united states has stationed in south vietnam nam as compared with the number of troops it has stationed in west germany.
知道为什么会这样吗?
luk2302 是正确的,尽管您最终会得到两个连续的空格,这种方法也必须解决。 我可以建议另一种更简单、更灵活的方法吗?
Map<String, String> replace = new HashMap<>();
replace.put("viet nam", "vietnam");
String line = "number of troops the united states has stationed in south viet nam as compared with the number of troops it has stationed in west germany .";
for (String key : replace.keySet()) {
line = line.replaceAll(key, replace.get(key));
}
您应该仔细考虑有关您替换什么的两个陈述,如果您将viet
替换为vietnam
,然后将nam
替换为空,那么您显然将再次替换刚刚替换的vietnam
的nam
。 导致viet nam
-> vietnam nam
-> viet nam
。
您可以通过简单地切换这两个语句来逃避:
line = line.replace(words[j+1].toLowerCase(), "");
line = line.replace(words[j].toLowerCase(), newWords.get(i).toLowerCase());
您实际上并不需要这两个replace
。
下面的代码经过测试并且工作正常。
public class Main {
public static void main(String args[]) {
String line = "in south viet nam as compared with the number of troops it has stationed in west germany";
ArrayList<String> newWords = new ArrayList<>();
newWords.add("vietnam");
newWords.add("India");
line = line.toLowerCase();
String[] words = line.split(" ");
for (int i = 0; i < newWords.size(); i++) {
for (int j = 0; j < words.length; j++) {
if(newWords.get(i).toLowerCase().equals(words[j].concat((j + 1 == words.length)?"":words[j+1]))){
line = line.replace((words[j] + " " + words[j+1]), newWords.get(i).toLowerCase());
}
}
}
System.out.println(line);
}
}
Output:
in south vietnam as compared with the number of troops it has stationed in west germany
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.