我实际上更喜欢 Code-Guru 的回答,但既然你说这只是一种好奇心,这里有一个递归解决方案。这个想法是只隔离您要替换的字符串的一部分并在其余部分上递归,这样我们就不会意外替换我们已经做过的东西。现在,如果您的两个规则有一个共同的前缀,您可能需要对规则进行一些排序才能获得所需的结果,但这里是:
public class ParallelReplace
{
public String replace(String s, Rule... rules)
{
return runRule(s, 0, rules);
}
private String runRule(String s, int curRule, Rule... rules)
{
if (curRule == rules.length)
{
return s;
}
else
{
Rule r = rules[curRule];
int index = s.indexOf(r.lhs);
if (index != -1)
{
return runRule(s.substring(0, index), curRule + 1, rules) + r.rhs
+ runRule(s.substring(index + r.rhs.length()), curRule + 1, rules);
}
else
{
return runRule(s, curRule + 1, rules);
}
}
}
public static class Rule
{
public String lhs;
public String rhs;
public Rule(String lhs, String rhs)
{
this.lhs = lhs;
this.rhs = rhs;
}
}
public static void main(String[] args)
{
String s = "foo1bar2";
ParallelReplace pr = new ParallelReplace();
System.out.println(pr.replace(s, new Rule("foo", "bar"), new Rule("bar", "foo")));
}
}