在java中,使用另一个数组中的单词替换数组中字符串中所有单词的最简单方法是什么?
例如,如果我有数组
["a", "b", "c"]
和["x", "y", "z"]
我如何获取字符串"a b c d e"
并将其转换为"x y z d e"
?
答案 0 :(得分:3)
可以找到您想要替换的单词的位置,从而将新值整合到这些位置:
String[] oldArray = {"a", "b", "c"};
String[] newArray = {"x", "y", "z"};
String text = "a b c d e";
int count = 0;
System.out.println("Text before: " + text);
for (String element : oldArray) {
if (text.contains(element)) {
text = text.substring(0, text.indexOf(element)) + newArray[count] + text.substring(text.indexOf(element) + 1, text.length());
}
count++;
}
System.out.println("Text after: " + text);
答案 1 :(得分:2)
也许使用 HashMap :
HashMap<String, String> map = new HashMap<>();
map.put("a", "x");
map.put("b", "y");
map.put("c", "z");
String string = "a b c d e";
for (Map.Entry<String, String> entry : map.entrySet()){
while (string.contains(entry.getKey())){
string = string.replace(entry.getKey(), entry.getValue());
}
}
答案 2 :(得分:1)
这是最直接的方式
String[] s1 = {"a", "b", "c"};
String[] s2 = {"x", "y", "z"};
String abc = "a b c d e";
for (int i = 0; i < s1.length; i++) {
abc = abc.replaceAll(s1[i], s2[i]);
}
System.out.println(abc);
输出:
x y z d e