24

Using C# how do I replace an item text in a string array if I don't know the position?

My array is [berlin, london, paris] how do I replace paris with new york?

2 Answers 2

38

You need to address it by index:

arr[2] = "new york";

Since you say you don't know the position, you can use Array.IndexOf to find it:

arr[Array.IndexOf(arr, "paris")] = "new york";  // ignoring error handling
Sign up to request clarification or add additional context in comments.

2 Comments

Why would IndexOf be unavailable in my array? I'm targeting .Net 3.5 Thanks
Mea culpa, Jade M, I am used to working with lists and didn't check the method docs. Sorry for the bad steer, answer updated.
13

You could also do it like this:

arr = arr.Select(s => s.Replace("paris", "new york")).ToArray();

2 Comments

This solution is quite dangerous. If you have similar strings they will be changed. For example you have: "York","Paris","New York",... If you want change "York" with "Berlin" you will have then: "Berlin","Paris","New Berlin",...
@tedebus Combine it with another answer then: stackoverflow.com/a/10151013/1033684

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.