在ASP.NET C#中假设我的字符串包含逗号分隔的单词:
string strOne = "word,WordTwo,another word, a third long word, and so on";
如何拆分然后与另一个可能包含或不包含这些词的段落进行比较:
string strTwo = " when search a word or try another word you may find that WordTwo is there with others";
然后如何输出这些常用词在第三个字符串中以逗号分隔
string strThree = "output1, output2, output3";
获得如下结果:" word,WordTwo,另一个词,"
答案 0 :(得分:3)
您需要用逗号 拆分 strOne,并对strTwo使用 包含 。
注意:您无法按空格分割strTwo并使用相交,因为您的项目可能包含空格。即"另一个词"
string strOne = "word,WordTwo,another word, a third long word, and so on";
string strTwo = " when search a word or try another word you may find that WordTwo is there with others";
var tokensOne = strOne.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var list = tokensOne.Where(x => strTwo.Contains(x));
var result = string.Join(", ",list);
答案 1 :(得分:2)
你可以这样做:
string strOne = "word,WordTwo,another word, a third long word, and so on";
string strTwo = " when search a word or try another word you may find that WordTwo is there with others";
string finalString = string.Empty;
foreach (var line in strOne.Split(","))
{
if(strTwo.Contains(line))
finalString += (line + ",");
}
finalString = finalString.Substring(0, finalString.Length - 1);
Console.WriteLine(finalString);