Logo

Programming-Idioms

Replace all exact occurrences of "foo" with "bar" in the string list x
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
(replace {"foo" "bar"} x)
std::replace(x.begin(), x.end(), "foo", "bar");
int i;
while ((i = x.IndexOf("foo")) != -1)
    x[i] = "bar";

x = x.map((e) => e == 'foo' ? 'bar' : e).toList();
for (var i = 0; i < x.length; i++) {
  if (x[i] == 'foo') x[i] = 'bar';
}
[case Elem of "foo" -> "bar"; _ -> Elem end || Elem <- X].
  where (x == "foo")
     x = "bar"
  endwhere
for i, v := range x {
	if v == "foo" {
		x[i] = "bar"
	}
}
func replaceAll[T comparable](s []T, old, new T) {
	for i, v := range s {
		if v == old {
			s[i] = new
		}
	}
}

replaceAll(x, "foo", "bar")
replaced = map (\e -> if e == "foo" then "bar" else e) x
x = x.map(e => e === 'foo' ? 'bar' : e);
import java.util.stream.Collectors;
x = x.stream()
     .map(s -> s.equals("foo") ? "bar" : s)
     .collect(Collectors.toList());
uses classes;
for i := 0 to x.count - 1 do
  if x[i] = 'foo' then
    x[i] := 'bar';
map { s/^foo$/bar/g } @x;
for i, v in enumerate(x):
  if v == "foo":
    x[i] = "bar"
x = ["bar" if v=="foo" else v for v in x]
x.map!{|el| el == "foo" ? "bar" : el}
for v in &mut x {
    if *v == "foo" {
        *v = "bar";
    }
}