Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace an item in a string array?

Tags:

arrays

c#

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?

like image 356
Jade M Avatar asked Feb 27 '10 23:02

Jade M


People also ask

How do you replace one item in an array?

To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

How do you replace an element in a string array in Java?

To replace an element in Java ArrayList, set() method of java. util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.

How do I replace a string in an array in VB net?

How do you replace text from an array using vb.net? $str = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '; $find = array('Lorem', 'sit', 'elit'); $replace = str_replace($find, '', $str);


2 Answers

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
like image 178
itowlson Avatar answered Oct 02 '22 22:10

itowlson


You could also do it like this:

arr = arr.Select(s => s.Replace("paris", "new york")).ToArray();
like image 23
Rob Sedgwick Avatar answered Oct 02 '22 22:10

Rob Sedgwick