我有两个字符串,其中包含以空格分隔的字母和数字。前任 “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");
关于C# 比较两个字符串的匹配词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3785064/