【问题标题】:Replace all occurences of a string from a string array替换字符串数组中所有出现的字符串
【发布时间】:2012-08-01 03:35:33
【问题描述】:

我有一个像这样的字符串数组:

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

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

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

我找到了一个解决方案How do I replace an item in a string array?

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

【问题讨论】:

  • 你关心数组中元素的顺序吗?
  • 我想知道如何在不访问该项目的情况下进行替换?
  • @Anirudha 想详细说明您所说的“那些优化”是什么意思?

标签: c# arrays string replace


【解决方案1】:
string [] items = {"one","two","three","one","two","one"};
items =  items.Select(s => s!= "one" ? s : "zero").ToArray();

here找到答案。

【讨论】:

  • 请注意,这会创建一个新数组。
  • 哎哟..还有更好的解决方案吗?
  • 如果您对数组有其他引用,保留原始数组可能很重要,否则您的解决方案当然可以,但它会在内部循环两次。一次用于计算数组长度的项目数,一次用于替换。请参阅 phoog 的回答。
【解决方案2】:

你也可以并行:

Parallel.For(0, items.Length,
  idx => { if(items[idx] == "one") { item[idx] = "zero"; } });

【讨论】:

    【解决方案3】:

    抱歉,您必须循环播放。没有办法绕过它。

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

    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<T>(this T[] items, T oldValue, T newValue)
        {
            for (int index = 0; index < items.Length; index++)
                if (items[index].Equals(oldValue))
                    items[index] = newValue;
        }
    }
    

    调用站点看起来一样。

    现在,这些方法都不支持自定义字符串相等检查。例如,您可能希望比较是否区分大小写。添加一个采用IEqualityComparer&lt;T&gt; 的重载,这样您就可以提供您喜欢的比较;这更加灵活,无论Tstring 还是其他:

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

    【讨论】:

      【解决方案4】:
      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;
      

      【讨论】:

        【解决方案5】:

        有一种方法可以在不循环遍历每个元素的情况下替换它:

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

        除此之外,您必须遍历数组(for/lambda/foreach)

        【讨论】:

          【解决方案6】:
          string[] newarry = items.Select(str => { if (str.Equals("one")) str = "zero"; return str; }).ToArray();
          

          【讨论】:

            【解决方案7】:

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

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

            【讨论】:

              【解决方案8】:

              没有循环就没有办法做到这一点。即使是这样的内部循环:

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

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

              【讨论】:

              • 这里如果 items 包含 "noone" ,它将被替换为 "nozero" ,rt?我需要准确地替换“一个”。
              • @Praveen:所以你原来的问题是错的?您对不循环执行它不感兴趣,并且您对用零替换所有出现的一不感兴趣?说你真正的问题是“如何在不使用 for/foreach/dowhile 循环的情况下在字符串数组中替换仅包含字母 'one' 的字符串”是否正确?
              猜你喜欢
              • 2021-12-27
              • 2022-11-21
              • 1970-01-01
              • 2017-03-20
              • 2011-02-23
              • 1970-01-01
              • 2013-12-06
              • 2019-01-10
              • 2018-07-11
              相关资源
              最近更新 更多