gpt4 book ai didi

c# - 遍历字符串数组并替换(如果存在)

转载 作者:行者123 更新时间:2023-12-02 04:44:31 24 4
gpt4 key购买 nike

我正在尝试遍历字符串数组并检查/替换输入字符串中是否存在任何字符串。使用 LINQ,这就是我目前所拥有的。

string input = "/main/dev.website.com"
string[] itemsToIgnore = { "dev.", "qa.", "/main/" };
string website = itemsToIgnore
.Select(x =>
{ x = input.Replace(x, ""); return x; })
.FirstOrDefault();

当我运行它时,实际上什么也没有发生,我的输入字符串保持不变?

最佳答案

string website = itemsToIgnore
.Aggregate(input, (current, s) =>
current.StartsWith(s) ? current.Replace(s, string.Empty) : current);

没有 Linq

foreach (var part in itemsToIgnore) 
{
if (website.StartsWith(part))
{
website = website.Replace(part, string.Empty);
}
}

关于c# - 遍历字符串数组并替换(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20057504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com