Replace all occurences of a string from a string array

前端 未结 8 1402
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 16:49

I have a string array like:

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

I would like to replace all ones with z

相关标签:
8条回答
  • 2020-12-11 16:54

    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.

    0 讨论(0)
  • 2020-12-11 16:57

    You can also do it in parallel:

    Parallel.For(0, items.Length,
      idx => { if(items[idx] == "one") { item[idx] = "zero"; } });
    
    0 讨论(0)
  • 2020-12-11 16:59

    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[]{','});
    
    0 讨论(0)
  • 2020-12-11 17:05
    string[] newarry = items.Select(str => { if (str.Equals("one")) str = "zero"; return str; }).ToArray();
    
    0 讨论(0)
  • 2020-12-11 17:07

    There is one way to replace it without looping through each element:

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

    Other than that, you have to iterate through the array (for/lambda/foreach)

    0 讨论(0)
  • 2020-12-11 17:09
    string [] items = {"one","two","three","one","two","one"};
    items =  items.Select(s => s!= "one" ? s : "zero").ToArray();
    

    Found answer from here.

    0 讨论(0)
提交回复
热议问题