搜索要替换的第一个单词。如果在字符串中,则在出现之前在字符串的一部分上递归,然后在出现之后在字符串的一部分上递归。
否则,继续下一个要替换的单词。
天真的实现可能看起来像这样
public static String replaceAll(String input, String[] search, String[] replace) {
return replaceAll(input, search, replace, 0);
}
private static String replaceAll(String input, String[] search, String[] replace, int i) {
if (i == search.length) {
return input;
}
int j = input.indexOf(search[i]);
if (j == -1) {
return replaceAll(input, search, replace, i + 1);
}
return replaceAll(input.substring(0, j), search, replace, i + 1) +
replace[i] +
replaceAll(input.substring(j + search[i].length()), search, replace, i);
}
用法示例:
String input = "Once upon a baz, there was a foo and a bar.";
String[] search = new String[] { "foo", "bar", "baz" };
String[] replace = new String[] { "bar", "baz", "foo" };
System.out.println(replaceAll(input, search, replace));
输出:
Once upon a foo, there was a bar and a baz.
一个不太天真的版本:
public static String replaceAll(String input, String[] search, String[] replace) {
StringBuilder sb = new StringBuilder();
replaceAll(sb, input, 0, input.length(), search, replace, 0);
return sb.toString();
}
private static void replaceAll(StringBuilder sb, String input, int start, int end, String[] search, String[] replace, int i) {
while (i < search.length && start < end) {
int j = indexOf(input, search[i], start, end);
if (j == -1) {
i++;
} else {
replaceAll(sb, input, start, j, search, replace, i + 1);
sb.append(replace[i]);
start = j + search[i].length();
}
}
sb.append(input, start, end);
}
不幸的是,Java String
没有indexOf(String str, int fromIndex, int toIndex)
方法。我indexOf
不确定这里的实现是正确的,但是我可以在ideone上找到它的实现,以及此处发布的各种解决方案的大致时间,因此省略了这里的实现。
swap(String s1, String s2, String s3)
可以s2
与s3
和交换所有出现的内容,反之亦然。