# 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

``x = ["bar" if v=="foo" else v for v in x]``
``````for i, v in enumerate(x):
if v == "foo":
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``````
``````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;``
``````x.map!{|el| el == "foo" ? "bar" : el}
``````
``````for v in &mut x {
if *v == "foo" {
*v = "bar";
}
}``````

programming-idioms.org