Say you have the following string:
cat dog fish dog fish cat
You want to replace all cats with dogs, all do
public class myreplase {
public Map replase;
public myreplase() {
replase = new HashMap();
replase.put("a", "Apple");
replase.put("b", "Banana");
replase.put("c", "Cantalope");
replase.put("d", "Date");
String word = "a b c d a b c d";
String ss = "";
Iterator i = replase.keySet().iterator();
while (i.hasNext()) {
ss += i.next();
if (i.hasNext()) {
ss += "|";
}
}
Pattern pattern = Pattern.compile(ss);
StringBuilder buffer = new StringBuilder();
for (int j = 0, k = 1; j < word.length(); j++,k++) {
String s = word.substring(j, k);
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
buffer.append(replase.get(s));
} else {
buffer.append(s);
}
}
System.out.println(buffer.toString());
}
public static void main(String[] args) {
new myreplase();
}
}
Output :- Apple Banana Cantalope Date Apple Banana Cantalope Date