Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurences of a string from a string array

I have a string array like:

 string [] items = {"one","two","three","one","two","one"};

I would like to replace all ones with zero at once. Then items should be:

{"zero","two","three","zero","two","zero"};

I found one solution How do I replace an item in a string array?.

But it will replace the first occurrence only. Which is the best method/approach to replace all occurrences?

like image 323
Praveen Prasannan Avatar asked Aug 03 '12 05:08

Praveen Prasannan


People also ask

How do you replace all occurrences in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

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

You can do String. replace('toreplace','replacement'). Iterate through each member of the array with a for loop.


2 Answers

Theres no way to do that without looping.. even something like this loops internally:

string [] items = {"one","two","three","one","two","one"};

string[] items2 = items.Select(x => x.Replace("one", "zero")).ToArray();

I'm not sure why your requirement is that you can't loop.. however, it will always need to loop.

like image 149
Simon Whitehead Avatar answered Sep 17 '22 07:09

Simon Whitehead


You can try this, but I think, It will do looping also.

string [] items = {"one","two","three","one","two","one"};
var str= string.Join(",", items);
var newArray = str.Replace("one","zero").Split(new char[]{','});
like image 30
Yograj Gupta Avatar answered Sep 20 '22 07:09

Yograj Gupta