1

Hey, I have an array of strings and I want to replace a certain substring in each of those elements. Is there an easy way to do that besides iterating the array explicitly?

Thanks :-)

2 Answers 2

6

Ultimately, anything you do is going to do exactly that anyway. A simple for loop should be fine. There are pretty solutions involving lambdas, such as Array.ConvertAll / Enumerable.Select, but tbh it isn't necessary:

for(int i = 0 ; i < arr.Length ; i++) arr[i] = arr[i].Replace("foo","bar");

(the for loop has the most efficient handling for arrays; and foreach isn't an option due to mutating the iterator variable)

Sign up to request clarification or add additional context in comments.

Comments

5

You could iterate the array implicitly

arrayOfStrings = arrayOfStrings.Select(s => s.Replace("abc", "xyz")).ToArray();

2 Comments

Strictly this does not replace elements in the array, it creates a new array with the replaced elements in. This makes i difference if the original arrayOfStrings was referenced elsewhere, like if arrayOfStrings was an in parameter in a method.
@grady you can not use foreach(var s in arrayOfStrings) {s = s.Replace("foo", "bar"); } since you are not allowed to modify the foreach variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.