【问题标题】:Compare and extract common words between 2 strings比较和提取 2 个字符串之间的常用词
【发布时间】:2018-04-21 02:44:46
【问题描述】:

在 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, another word,"

【问题讨论】:

  • 这与 asp.net 有什么关系。这不只是一个 C# 问题吗?
  • 用逗号分割strOne,用空格分割strTwo。然后使用intersectLINQ 方法获取两个数组中存在的常用词。 stackoverflow.com/questions/10323071/…
  • 可能是因为我正在构建一个 ASP.NET 应用程序:),应该删除它:)
  • 你希望输出重复单词还是不同
  • 不要只得到他们一次@TheGeneral

标签: c# string


【解决方案1】:

您需要用逗号拆分 strOne,并使用 contains 对 strTwo。

注意:你不能用空格分割 strTwo 并使用 intersect 因为你的项目可能有空格。即“另一个词”

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

【讨论】:

  • 感谢@Drew 为我工作并在不同的场景下进行测试
【解决方案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);

【讨论】:

  • 好答案。如果您使用List 代替finalString,则可以使用string.Join 将其以逗号分隔。
  • 如果不是string.Join,那么考虑使用StringBuilder 代替finalString,而不是每次都连接字符串。
  • strOne.Split(",") 无效。查看 hsobhy 的评论
  • strOne.Split(',') 代替
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多