Replace all occurences of a string from a string array

前端 未结 8 1444
伪装坚强ぢ
伪装坚强ぢ 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 17:10

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

    If you want it the index way as you specified:

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

    But LINQ would be better

    var lst = from item in items
    select item == "one" ? "zero" : item;
    

提交回复
热议问题