从字符串数组中替换字符串的所有出现

我有一个像以下字符串数组:

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

我想立刻用零替换所有的。 那么项目应该是:

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

我找到了一个解决方案如何替换字符串数组中的项? 。

但它只会取代第一次出现。 替换所有事件的最佳方法/方法是哪种?

如果没有循环,没有办法做到这一点..甚至这样的内部循环:

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

我不确定为什么你的要求是你不能循环..但是,它总是需要循环。

有一种方法可以替换它而不循环遍历每个元素:

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

除此之外,你必须遍历数组(对于/ lambda / foreach)

对不起,你必须循环。 没有绕过它。

此外,所有其他答案都会为您提供一个包含所需元素的新数组 。 如果你想让同一个数组修改它的元素,正如你的问题所暗示的那样,你应该这样做。

 for (int index = 0; index < items.Length; index++) if (items[index] == "one") items[index] = "zero"; 

简单。

为避免每次需要时都在代码中编写循环,请创建一个方法:

 void ReplaceAll(string[] items, string oldValue, string newValue) { for (int index = 0; index < items.Length; index++) if (items[index] == oldValue) items[index] = newValue; } 

然后这样称呼它:

 ReplaceAll(items, "one", "zero"); 

您还可以将其转换为扩展方法:

 static class ArrayExtensions { public static void ReplaceAll(this string[] items, string oldValue, string newValue) { for (int index = 0; index < items.Length; index++) if (items[index] == oldValue) items[index] = newValue; } } 

然后你可以像这样调用它:

 items.ReplaceAll("one", "zero"); 

当你在它的时候,你可能想让它变得通用:

 static class ArrayExtensions { public static void ReplaceAll(this T[] items, T oldValue, T newValue) { for (int index = 0; index < items.Length; index++) if (items[index].Equals(oldValue)) items[index] = newValue; } } 

呼叫站点看起来一样。

现在,这些方法都不支持自定义字符串相等性检查。 例如,您可能希望比较区分大小写或不区分大小写。 添加一个带有IEqualityComparer的重载,这样你就可以提供你喜欢的比较; 这是更灵活的,无论Tstring还是别的东西:

 static class ArrayExtensions { public static void ReplaceAll(this T[] items, T oldValue, T newValue) { items.ReplaceAll(oldValue, newValue, EqualityComparer.Default); } public static void ReplaceAll(this T[] items, T oldValue, T newValue, IEqualityComparer comparer) { for (int index = 0; index < items.Length; index++) if (comparer.Equals(items[index], oldValue)) items[index] = newValue; } } 

您也可以并行执行:

 Parallel.For(0, items.Length, idx => { if(items[idx] == "one") { item[idx] = "zero"; } }); 
 string [] items = {"one","two","three","one","two","one"}; items = items.Select(s => s!= "one" ? s : "zero").ToArray(); 

从这里找到答案。

你可以尝试这个,但我认为,它也会循环。

 string [] items = {"one","two","three","one","two","one"}; var str= string.Join(",", items); var newArray = str.Replace("one","zero").Split(new char[]{','}); 
 string[] items = { "one", "two", "three", "one", "two", "one" }; 

如果你想要它你指定的索引方式:

 int n=0; while (true) { n = Array.IndexOf(items, "one", n); if (n == -1) break; items[n] = "zero"; } 

但LINQ会更好

 var lst = from item in items select item == "one" ? "zero" : item; 
 string[] newarry = items.Select(str => { if (str.Equals("one")) str = "zero"; return str; }).ToArray();