First, a demonstration of the problem:
String s = "I have three cats and two dogs.";
s = s.replace("cats", "dogs")
.replace("dogs", "budgies");
System.out.println(s);
目的是取代cat =>狗和狗 => budgies,但按顺序进行的更换是根据先前的更换结果进行的,因此,不幸的产出是:
I have three budgies and two budgies.
在此,我同时采用了替代方法。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#regionMatches%28boolean,%20int,%20java.lang.String,%20int,%20int%29”rel=“nofollow”String.regionches
:
public static String simultaneousReplace(String subject, String... pairs) {
if (pairs.length % 2 != 0) throw new IllegalArgumentException(
"Strings to find and replace are not paired.");
StringBuilder sb = new StringBuilder();
int numPairs = pairs.length / 2;
outer:
for (int i = 0; i < subject.length(); i++) {
for (int j = 0; j < numPairs; j++) {
String find = pairs[j * 2];
if (subject.regionMatches(i, find, 0, find.length())) {
sb.append(pairs[j * 2 + 1]);
i += find.length() - 1;
continue outer;
}
}
sb.append(subject.charAt(i));
}
return sb.toString();
}
测试:
String s = "I have three cats and two dogs.";
s = simultaneousReplace(s,
"cats", "dogs",
"dogs", "budgies");
System.out.println(s);
产出:
我有三支狗和两台gie。
此外,有时在同时更换时也是有益的,以确保寻找最长的配对。 (PHP s strtr function do this, for example.) 下面是我执行:
public static String simultaneousReplaceLongest(String subject, String... pairs) {
if (pairs.length % 2 != 0) throw new IllegalArgumentException(
"Strings to find and replace are not paired.");
StringBuilder sb = new StringBuilder();
int numPairs = pairs.length / 2;
for (int i = 0; i < subject.length(); i++) {
int longestMatchIndex = -1;
int longestMatchLength = -1;
for (int j = 0; j < numPairs; j++) {
String find = pairs[j * 2];
if (subject.regionMatches(i, find, 0, find.length())) {
if (find.length() > longestMatchLength) {
longestMatchIndex = j;
longestMatchLength = find.length();
}
}
}
if (longestMatchIndex >= 0) {
sb.append(pairs[longestMatchIndex * 2 + 1]);
i += longestMatchLength - 1;
} else {
sb.append(subject.charAt(i));
}
}
return sb.toString();
}
为什么你们需要这样做? 例如下:
String truth = "Java is to JavaScript";
truth += " as " + simultaneousReplaceLongest(truth,
"Java", "Ham",
"JavaScript", "Hamster");
System.out.println(truth);
产出:
贾瓦语是 Java语,因为Hamster
如果我们使用<代码>传真编码>而不是<编码>传真<<<>同时语文代码>,则产出将具有“Hamgust”而不是“Hamster”:
请注意,上述方法对个案敏感。 如果您需要对个案敏感的版本,很容易修改上述文本,因为<代码>String.regionMatches/code>可采用ignore。 判例编码>参数。