我正在尝试创建一个程序,可以缩写用户给出的字符串中的某些单词。
到目前为止,这就是我的解决方法:
从.txt文件创建一个hashmap,如下所示:
thanks,thx
your,yr
probably,prob
people,ppl
在我尝试更新字符串之前,一切正常:
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
有谁知道如何更新字符串中的所有单词?
提前致谢
答案 0 :(得分:4)
updatedstring = rawstring.replace(word, x);
这会一直用rawstring替换你的updatedstring并使用单个替换。
您需要执行类似
的操作updatedstring = rawstring;
...
updatedString = updatedString.replace(word, x);
<小时/> 编辑:
这是您遇到的问题的解决方案,但您的代码还存在一些其他问题:
您的替换不适用于您需要降低字符或删除字符的内容。您可以创建从您的rawstring的更改版本迭代的单词数组。然后,您返回并尝试从原始rawstring中替换不存在的更改版本。这将找不到您认为要替换的词语。
如果你正在进行全局替换,你可以创建一组单词而不是数组,因为一旦替换了单词,它就不会再出现了。
您可能希望一次更换一个单词,因为您的全局替换可能会导致奇怪的错误,其中替换地图中的单词是另一个替换单词的子单词。而不是使用String.replace,创建一个数组/单词列表,迭代单词并在需要时替换列表中的元素并加入它们。在java 8中:
String.join(" ", elements);