快速多重字符串比较[英] Fast multiple string compare

本文是小编为大家收集整理的关于快速多重字符串比较的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在C#中,有一种快速的方法可以用更有效的代码替换以下内容:

string letters = "a,b,c,d,e,f";

if (letters.Contains("a"))
{
    return true;
}

if (letters.Contains("b"))
{
    return true;
}

if (letters.Contains("c"))
{
    return true;
}

我想取消必须有三个比较行的代码.

谢谢!

推荐答案

您可以使用类似的东西:

return letters.Any(c => c == 'a' || c == 'b' || c == 'c');

或以下:

var lettersToLookFor = "abc";
return letters.Any(c => lettersToLookFor.Contains(c));

根据评论,可以进一步缩短上一句话的最后一行:

return letters.Any(lettersToLookFor.Contains);

其他推荐答案

如果您实际上在字符串中寻找单个字符,则可以使用IndexOfAny

return letters.IndexOfAny('a', 'b', 'c') >= 0;

它使整个字符串中的一个通过,并将字符串中的每个字符与传递的字符进行比较.

如果没有任何字符,它仍然是m * n比较(与上述相同3),但是如果确实存在任何字符,则它会更快地从道奇上出来.
同样对于更长的字符串,它在CPU缓存内存上是友善的.

其他推荐答案

您可以使用Intersect查看两个字符集之间是否有任何共同的字符.请注意,字符串实现IEnumerable<char>,因此您可以将所有字符串视为字符的序列.

bool result = "abc".Intersect(letters).Any();

请注意,该解决方案将使所有字符从letters中放入HashSet中,都比当前在字符串上执行多个线性搜索的其他解决方案(假设字符串)更有效是一个非平凡的大小,搜索字符在开始附近不正确. (您确实说效率很重要.)

本文地址:https://www.itbaoku.cn/post/1557197.html

问题描述

In c# is there a quick way to replace the following with more efficient code:

string letters = "a,b,c,d,e,f";

if (letters.Contains("a"))
{
    return true;
}

if (letters.Contains("b"))
{
    return true;
}

if (letters.Contains("c"))
{
    return true;
}

I want to do away with having to have three compare lines of code.

Thanks!

推荐答案

You could use something like this:

return letters.Any(c => c == 'a' || c == 'b' || c == 'c');

Or this:

var lettersToLookFor = "abc";
return letters.Any(c => lettersToLookFor.Contains(c));

As per the comments, the last line of the previous code block can be shortened further:

return letters.Any(lettersToLookFor.Contains);

其他推荐答案

If you're literally looking for single characters in a string you can use IndexOfAny

return letters.IndexOfAny('a', 'b', 'c') >= 0;

It makes one pass over the entire string and compares each char in the string against the chars passed in.

If none of the chars exist it's still M * N comparisons (same as 3 if's above), but if any char does exist it gets out of dodge faster.
Also for longer strings it's kinder on CPU cache memory.

其他推荐答案

You can use Intersect to see if there are any characters in common between the two character sets. Note that strings implement IEnumerable<char>, so you can treat all strings as just sequences of characters.

bool result = "abc".Intersect(letters).Any();

Note that this solution, as it will put all of the characters from letters into a HashSet, will be dramatically more efficient than the other solutions currently posted that are performing multiple linear searches on the string, assuming the string is of a non-trivial size, and the search characters are not right near the start. (You did say efficiency mattered.)