C#比较两个匹配单词的字符串

Mar*_*wan 6 c# string

我有两个包含字母和数字的字符串,用空格分隔.前"elza7ma wa2fa fel matab"和"2ana ba7eb el za7ma 2awy 2awy"

比较这两个字符串以查明它们是否有共同字的最快方法是什么?

我尝试使用string.split拆分其中一个,并在整个单词数组中使用string.compare.但这很慢,因为我会比较很多字符串.

Rus*_*Cam 14

LINQ解决方案

"elza7ma wa2fa fel matab".Split()
                         .Intersect("2ana ba7eb el za7ma 2awy 2awy".Split())
                         .Any();

// as a string extension method
public static class StringExtensions
{
    public static bool OneWordMatches(this string theString, string otherString)
    {
        return theString.Split().Intersect(otherString.Split()).Any();
    }
}

// returns true
"elza7ma wa2fa fel matab 2ana".OneWordMatches("2ana ba7eb el za7ma 2awy 2awy");
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 5

我认为最简单的方法是将字符串分解为单词并使用集合结构HashSet<string>来检查重复项.例如

public bool HasMatchingWord(string left, string right) { 
  var hashSet = new HashSet<string>(
    left.Split(" ", StringSplitOptions.RemoveEmptyEntries)); 
  return right
    .Split(" ", StringSplitOptions.RemoveEmptyEntries)
    .Any(x => hashSet.Contains(x));
}
Run Code Online (Sandbox Code Playgroud)