开发者

What's the most terse way to write a bunch of String.replaceAll("thing1", "thing2"); statements? [closed]

开发者 https://www.devze.com 2023-03-26 11:09 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous开发者_Go百科, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. F
It's difficult to tell what is being asked here. This question is ambiguous开发者_Go百科, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消