我有两个包含字母和数字的字符串,由空格分隔。例如:"elza7ma wa2fa fel matab" 和 "2ana ba7eb el za7ma 2awy 2awy"
最快的方法是什么,可以比较这两个字符串并找出它们是否有相同的单词?
我尝试使用 string.split 将其中一个字符串拆分,并在整个单词数组上使用 string.compare 进行比较。但这非常慢,因为我将比较很多字符串。
我有两个包含字母和数字的字符串,由空格分隔。例如:"elza7ma wa2fa fel matab" 和 "2ana ba7eb el za7ma 2awy 2awy"
最快的方法是什么,可以比较这两个字符串并找出它们是否有相同的单词?
我尝试使用 string.split 将其中一个字符串拆分,并在整个单词数组上使用 string.compare 进行比较。但这非常慢,因为我将比较很多字符串。
一个 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");
我认为最简单的方法是将字符串拆分为单词,并使用类似于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));
}
Dictionary<string, int>
)。如果第三个字典中的任何键计数超过一,则该单词在原始字符串中都存在。我可能会承受最初的性能损失,将字符串拆分并按字母顺序和单词长度排序。 如果你只需要找出一个单词是否匹配,那么一旦找到一个就可以停止。 一旦你将拆分的字符串数组按字母顺序和长度排序,这就限制了你需要进行比较的数量。