Remove specific char in all strings in a list in c

2019-03-07 07:19发布

问题:

I have some strings in a list they are

KHIJEFGACDB
KHIJEFGBACD
KHIJEFGBCDA
KHIJEFGCDAB
KHIJEFGCDBA
KHIJGABCDEF
KHIJGABEFCD
KHIJGACDBEF
KHIJGACDEFB
KHIJGAEFBCD
KHIJGAEFCDB
KHIJGBACDEF
KHIJGBAEFCD

I need to remove HIJ which is available in all strings in the list.

I made a C# program like below

foreach (string item in items)
{
    item.Replace("HIJ", "");
}
Console.WriteLine(items.FirstOrDefault().Length);

But its still displaying 11 that means the HIJ is not removed. How to solve this and get 8 as the answer.

回答1:

Strings are immutable in C#. Try

for (int i = 0; i < items.Length; i++)
    items[i] = items[i].Replace("HIJ", "");

Also note within

foreach (string item in items)

item cannot be modified. And, BTW, foreach can not be used to add or remove items from the source collection to avoid unpredictable side effects. See http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx.



回答2:

As noted, strings are immutable. string.Replace() returns a new string: it doesn't modify the existing string.

But you can do this in one line using Linq, something like this:

string[] items = GetMeSomeItems()
                 .Select( s => s.Replace("HIJ","") )
                 .ToArray()
                 ;


标签: c# list replace