Java 将一个数组中字符串中的所有单词替换为另一个数组中相同位置的单词
在java中,用另一个数组中的单词替换数组中字符串中的所有单词最简单的方法是什么 例如,如果我有数组Java 将一个数组中字符串中的所有单词替换为另一个数组中相同位置的单词,java,Java,在java中,用另一个数组中的单词替换数组中字符串中的所有单词最简单的方法是什么 例如,如果我有数组 [“a”、“b”、“c”]和[“x”、“y”、“z”] 我如何将字符串“abcde”转换为“xyzdee”?可能使用HashMap这样的方法: HashMap map=newhashmap(); 地图放置(“a”、“x”); 地图放置(“b”、“y”); 地图放置(“c”、“z”); String String=“a b c d e”; 对于(Map.Entry:Map.entrySet()){
[“a”、“b”、“c”]
和[“x”、“y”、“z”]
我如何将字符串“abcde”
转换为“xyzdee”
?可能使用HashMap这样的方法:
HashMap map=newhashmap();
地图放置(“a”、“x”);
地图放置(“b”、“y”);
地图放置(“c”、“z”);
String String=“a b c d e”;
对于(Map.Entry:Map.entrySet()){
while(string.contains(entry.getKey())){
string=string.replace(entry.getKey(),entry.getValue());
}
}
可能使用哈希映射:
HashMap map=newhashmap();
地图放置(“a”、“x”);
地图放置(“b”、“y”);
地图放置(“c”、“z”);
String String=“a b c d e”;
对于(Map.Entry:Map.entrySet()){
while(string.contains(entry.getKey())){
string=string.replace(entry.getKey(),entry.getValue());
}
}
可以找到要替换的单词的位置,从而将新值整合到这些位置:
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);
可以找到要替换的单词的位置,从而将新值整合到这些位置:
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);
这是最直接的方法
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);
这是最直接的方法
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);