Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #254 Replace value in list

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

uses classes;
for i := 0 to x.count - 1 do
  if x[i] = 'foo' then
    x[i] := 'bar';
(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
func replaceAll[T comparable](s []T, old, new T) {
	for i, v := range s {
		if v == old {
			s[i] = new
		}
	}
}

replaceAll(x, "foo", "bar")
for i, v := range x {
	if v == "foo" {
		x[i] = "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());
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";
    }
}

New implementation...