如何使用特定单词“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到x不同的单词
答案 0 :(得分: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