23

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jade M
  • 3,031
  • 6
  • 26
  • 25

2 Answers2

37

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
itowlson
  • 73,686
  • 17
  • 161
  • 157
  • Why would IndexOf be unavailable in my array? I'm targeting .Net 3.5 Thanks – Jade M Feb 27 '10 at 23:32
  • 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. – itowlson Feb 27 '10 at 23:47
13

You could also do it like this:

arr = arr.Select(s => s.Replace("paris", "new york")).ToArray();
Rob Sedgwick
  • 4,342
  • 6
  • 50
  • 87
  • 3
    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 Sep 26 '18 at 09:12
  • @tedebus Combine it with another answer then: https://stackoverflow.com/a/10151013/1033684 – Rob Sedgwick Sep 26 '18 at 13:08