我'试图删除特定列出的值:
var List = new List<string> { "sun", "open", "look", "night", "cat"};
来自字符串:
string str = "hello, sunday, opening, look, midnight, cat"
像这样:
string[] inputs = str.Split(' ');
StringBuilder sbResult = new StringBuilder();
foreach (var input in inputs)
{
if (!List.Contains(input))
{
sbResult.AppendFormat("{0} ", input);
}
}
string result = sbResult.ToString().Trim();
但这种方式只适用于相同的单词,但如果列出的单词与其他单词合并则不会删除:
"hello, sunday, opening, midnight"
并且所需的输出必须是:
"hello, day, ing, mid"
我必须在这里注意两件事,我想在List中使用它来获取大约90000的值,输入字符串长约100字甚至更多
答案 0 :(得分:2)
用一行解决方案给你的教授留下深刻印象!
string str = "hello, sunday, opening, look, midnight, cat";
var list = new List<string> { "sun", "open", "look", "night", "cat" };
list.ForEach(a => str = str.Replace(a, ""));
Console.WriteLine(str);
答案 1 :(得分:1)
var keywordList = new List<string> { "sun", "open", "look", "night", "cat"};
string str = "hello, sunday, opening, look, midnight, cat";
var strList = str.Split(',').Select(i => i.Trim()).ToList();
foreach (var keyword in keywordList)
{
for (int i = 0; i < strList.Count; i++)
{
strList[i] = strList[i].Replace(keyword, String.Empty);
}
}
str = strList.Where(i => i != String.Empty).Aggregate((a, b) => a + ", " + b);