पहले, समस्या का एक प्रदर्शन:
String s = "I have three cats and two dogs.";
s = s.replace("cats", "dogs")
.replace("dogs", "budgies");
System.out.println(s);
यह बिल्लियों => कुत्तों और कुत्तों => budgies को बदलने के लिए इरादा है, लेकिन अनुक्रमिक प्रतिस्थापन पिछले आर के परिणाम पर चल रही है प्रतिस्थापन, इसलिए दुर्भाग्यपूर्ण आउटपुट है:
मेरे पास तीन budgies और दो budgies है।
यहां एक साथ प्रतिस्थापन विधि का मेरा कार्यान्वयन है। यह String.regionMatches
का उपयोग कर लिखने के लिए आसान है:
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);
आउटपुट:
मैं तीन कुत्तों और दो budgies की है।
इसके अतिरिक्त, यह कभी-कभी उपयोगी होता है जब यह एक साथ प्रतिस्थापन करता है, ताकि सबसे लंबा मैच देखने के लिए सुनिश्चित किया जा सके। (PHP के strtr
फ़ंक्शन यह उदाहरण के लिए करता है।) यहां इसके लिए मेरा कार्यान्वयन है:
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);
आउटपुट:
जावा जावास्क्रिप्ट करने के लिए है हम simultaneousReplaceLongest
की simultaneousReplace
बजाय, उत्पादन पड़ता था "HamScript" का इस्तेमाल किया था, तो के रूप में हाम हैम्स्टर
है "हैम्स्टर" के बजाय :)
ध्यान दें कि उपरोक्त विधियां केस-संवेदी हैं। यदि आपको केस-असंवेदनशील संस्करणों की आवश्यकता है तो उपरोक्त को संशोधित करना आसान है क्योंकि String.regionMatches
ignoreCase
पैरामीटर ले सकता है।
संबंधित धागा - http://stackoverflow.com/questions/2049528/java-best-way-for-string-find-and-replace – adatapost