C# 比较并提取两个字符串之间的常用词

C# 比较并提取两个字符串之间的常用词,c#,string,C#,String,在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"; 那么如何

在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,另一个词,”

您可以这样做:

        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);

你可以这样做:

        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);
您需要通过逗号分割字符串,并对strTwo使用包含

注意:您不能按空格分割strTwo并使用intersect,因为您的项目可能有空格。i、 e.“另一个词”

您需要通过逗号分割字符串,并对strTwo使用包含

注意:您不能按空格分割strTwo并使用intersect,因为您的项目可能有空格。i、 e.“另一个词”


这与asp.net有什么关系。这不只是一个C#问题吗?按逗号拆分
strOne
,按空格拆分
strTwo
。然后使用
intersect
LINQ方法获取两个数组中存在的公共词。可能是因为我正在构建一个ASP.NET应用程序:),应该将其删除:)你想让输出重复单词或词组吗?不要只获取一次@TheGeneral这与ASP.NET有什么关系。这不只是一个C#问题吗?按逗号拆分
strOne
,按空格拆分
strTwo
。然后使用
intersect
LINQ方法获取两个数组中存在的公共词。可能是因为我正在构建一个ASP.NET应用程序:),应该将其删除:)您希望输出重复单词还是区分,而不是只获取一次@generalgood答案。如果使用<代码>列表/<代码> <代码> FialString ,则可以使用“代码>字符串”。“加入/<代码>使其逗号分隔。如果不是<代码>字符串。加入< /代码>,然后考虑使用<代码> StringBuilder <代码> <代码> FielString ,而不是每次串接。Stron.S拆除(“,”)无效。请参阅hsobhy的commentstrOne.Split(','),而不是正确答案。如果使用<代码>列表/<代码> <代码> FialString ,则可以使用“代码>字符串”。“加入/<代码>使其逗号分隔。如果不是<代码>字符串。加入< /代码>,然后考虑使用<代码> StringBuilder <代码> <代码> FielString ,而不是每次串接。Stron.S拆除(“,”)无效。参见hsobhy的CommentsRone.Split(“,”)代替感谢@Drew为我工作并用不同的场景进行测试Hank@Drew为我工作并用不同的场景进行测试