Java-一次更改字符串中的多个单词?
我正在尝试创建一个程序,可以在用户给定的字符串中缩写某些单词 到目前为止,我是这样安排的: 从.txt文件创建哈希映射,如下所示:Java-一次更改字符串中的多个单词?,java,string,Java,String,我正在尝试创建一个程序,可以在用户给定的字符串中缩写某些单词 到目前为止,我是这样安排的: 从.txt文件创建哈希映射,如下所示: thanks,thx your,yr probably,prob people,ppl 从用户处获取字符串 将字符串拆分为单词 检查hashmap以查看该单词是否作为键存在 使用hashmap.get()返回键值 用返回的键值替换单词 返回更新的字符串 在我尝试更新字符串之前,一切都非常正常: public String shortenMessage( Str
thanks,thx
your,yr
probably,prob
people,ppl
- 从用户处获取字符串
- 将字符串拆分为单词
- 检查hashmap以查看该单词是否作为键存在
- 使用hashmap.get()返回键值
- 用返回的键值替换单词
- 返回更新的字符串
public String shortenMessage( String inMessage ) {
String updatedstring = "";
String rawstring = inMessage;
String[] words = rawstring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
for (String word : words) {
System.out.println(word);
if (map.containsKey(word) == true) {
String x = map.get(word);
updatedstring = rawstring.replace(word, x);
}
}
System.out.println(updatedstring);
return updatedstring;
}
输入:
thanks, your, probably, people
输出:
thanks, your, probably, ppl
有人知道如何更新字符串中的所有单词吗
提前谢谢
updatedstring = rawstring.replace(word, x);
这会不断地用单个替换的原始字符串替换updatedstring
你需要像这样做
updatedstring = rawstring;
...
updatedString = updatedString.replace(word, x);
编辑: 这就是您看到的问题的解决方案,但您的代码还有一些其他问题:
String.join(“,元素)代码>
updatedstring = rawstring;
...
updatedString = updatedString.replace(word, x);
编辑: 这就是您看到的问题的解决方案,但您的代码还有一些其他问题:
String.join(“,元素)代码>
Debug
再多一点。在您的if(map.containsKey(word))
中打印x
,然后打印updatedstring
,并查看结果。编辑:我有自己的想法(虽然我不确定),但@DTing指出并证实了我的想法。永远不要这样做-if(map.containsKey(word)==true)
;始终编写if(map.containsKey(word))
。马上改掉这个习惯。Debug
再多一点。在您的if(map.containsKey(word))
中打印x
,然后打印updatedstring
,并查看结果。编辑:我有自己的想法(虽然我不确定),但@DTing指出并证实了我的想法。永远不要这样做-if(map.containsKey(word)==true)
;始终编写if(map.containsKey(word))
。马上改掉那个习惯。