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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11789750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:16:19  来源:igfitidea点击:

Replace all occurences of a string from a string array

c#arraysstringreplace

提问by Praveen Prasannan

I have a string array like:

我有一个字符串数组,如:

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

I would like to replace all ones with zero at once. Then items should be:

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

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

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

I found one solution How do I replace an item in a string array?.

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

But it will replace the first occurrence only. Which is the best method/approach to replace all occurrences?

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

采纳答案by Praveen Prasannan

string [] items = {"one","two","three","one","two","one"};
items =  items.Select(s => s!= "one" ? s : "zero").ToArray();

Found answer from here.

这里找到答案。

回答by Simon Whitehead

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.

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

回答by benjamin54

string[] newarry = items.Select(str => { if (str.Equals("one")) str = "zero"; return str; }).ToArray();

回答by Yograj Gupta

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[]{','});

回答by Anirudha

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

但是LINQ会更好

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

回答by Daniel MesSer

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)

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

回答by phoog

Sorry, you have to loop. There's no getting around it.

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

Also, all of the other answers give you a new arraywith the desired elements. If you want the same arrayto have its elements modified, as your question implies, you should just do it like this.

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

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

Simple.

简单的。

To avoid writing a loop in your code every time you need this to happen, create a method:

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

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

Then call it like this:

然后像这样调用它:

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

You can also make it into an extension method:

你也可以把它变成一个扩展方法:

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;
    }
}

Then you can call it like this:

然后你可以这样称呼它:

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

While you're at it, you might want to make it generic:

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

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;
    }
}

The call site looks the same.

呼叫站点看起来相同。

Now, none of these approaches supports custom string equality checking. For example, you might want the comparison to be case sensitive, or not. Add an overload that takes an IEqualityComparer<T>, so you can supply the comparison you like; this is much more flexible, whether Tis stringor something else:

现在,这些方法都不支持自定义字符串相等性检查。例如,您可能希望比较区分大小写。添加一个带有 的重载IEqualityComparer<T>,以便您可以提供您喜欢的比较;这更加灵活,无论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;
    }
}

回答by Jeppe Stig Nielsen

You can also do it in parallel:

您也可以并行执行:

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