What's the most terse way to write a bunch of String.replaceAll("thing1", "thing2"); statements? [closed]
I feel like I could do something with linked lists, but I'm not quite sure how to implement it.
~Sigh~ I would love this in python. Would just use dictionaries.
Thanks a lot, statue
String strOutput = src.replace("foo","foo2").replace("bar","bar2");
or, if you have many more replacements, store them in an array:
//array to hold replacements
String[][] replacements = {{"foo", "foo2"},
{"bar", "bar2"}};
//loop over the array and replace
for(String[] replacement: replacements) {
src = src.replace(replacement[0], replacement[1]);
}
If I understand you correctly you want to do a bunch of replacements after another on the same string (replace a by b, c by d etc...)
you could do that in a map like this
String toreplace = ...
Map<String, String> replacements = new HashMap<String, String>();
replacments.put("A","B");
replacments.put("C","D");
replacments.put("D","E");
for (Entry curReplacement : replacments.entryMap())
{
toReplace.replaceAll(curReplacement.getKey(),curReplacement.getValue())
}
Be carfeul though. You cannot predict the order of replacements, as soon as you have overlapping replacments (e.g. replace a by b and b by c) you cannot predict the outcome (in this case an OrderedHashMap would be the better solution)
精彩评论