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?
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.
You can do String. replace('toreplace','replacement'). Iterate through each member of the array with a for loop.
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.
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[]{','});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With