【问题标题】:How to replace different words from list found in string with specific word如何用特定单词替换字符串中找到的列表中的不同单词
【发布时间】:2017-04-26 05:54:56
【问题描述】:

如何用特定单词“x”替换字符串中列表中的不同单词:

string str = "how to replace different words from list found in string with specific word"; 

var valueList = new List<string> { "replace", "string", "specific", "found", "how", "word"};  

if (valueList.Any(str.Contains))   
{
   //...                       
}

如果使用 if 语句,我可以一一做到 str.Replace("replace", "x"); 等,但不确定如何从列出的值中正确获得相同的结果:

x 到 x 与 x x 的列表 x 中的 x 不同的单词

【问题讨论】:

    标签: c# string list replace


    【解决方案1】:

    具有 Linq 风味:

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            string str = "how to replace different words from list found in string with specific word"; 
    
            var valueList = new List<string> { "replace", "string", "specific", "found", "how", "word"};  
    
            var result = valueList.Aggregate(str, (current, c) => current.Replace(c, "x"));
    
            Console.WriteLine(result);
        }
    }
    

    编辑:

    .NET 小提琴:https://dotnetfiddle.net/BVJphf

    【讨论】:

    • 我不知道。我建议你运行一些基准测试。我只是想提出一个 Linq 解决方案 :-)
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 2016-01-29
    • 2014-01-08
    • 2012-09-14
    • 2021-06-30
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多