简体   繁体   English

C# 检查字符串是否包含字符串数组中的任何匹配项

[英]C# Check if string contains any matches in a string array

What would be the fastest way to check if a string contains any matches in a string array in C#?检查字符串是否在 C# 中的字符串数组中包含任何匹配项的最快方法是什么? I can do it using a loop, but I think that would be too slow.我可以使用循环来完成,但我认为这太慢了。

Using LINQ:使用 LINQ:

 return array.Any(s => s.Equals(myString))

Granted, you might want to take culture and case into account, but that's the general idea.当然,您可能希望将文化和案例考虑在内,但这是总体思路。 Also, if equality is not what you meant by "matches", you can always you the function you need to use for "match".此外,如果相等不是您所说的“匹配”的意思,您总是可以使用您需要用于“匹配”的函数。

I really couldn't tell you if this is absolutely the fastest way, but one of the ways I have commonly done this is:我真的无法告诉你这是否绝对是最快的方法,但我通常这样做的方法之一是:

This will check if the string contains any of the strings from the array:这将检查字符串是否包含数组中的任何字符串:

string[] myStrings = { "a", "b", "c" };
string checkThis = "abc";

if (myStrings.Any(checkThis.Contains))
{
    MessageBox.Show("checkThis contains a string from string array myStrings.");
}

To check if the string contains all the strings (elements) of the array, simply change myStrings.Any in the if statement to myStrings.All .要检查是否字符串包含数组的所有字符串(元素),只需更改myStrings.Any在if语句myStrings.All

I don't know what kind of application this is, but I often need to use:我不知道这是一个什么样的应用程序,但我经常需要使用:

if (myStrings.Any(checkThis.ToLowerInvariant().Contains))

So if you are checking to see user input, it won't matter, whether the user enters the string in CAPITAL letters, this could easily be reversed using ToLowerInvariant().因此,如果您正在检查用户输入,那么用户是否以大写字母输入字符串并不重要,这可以使用 ToLowerInvariant() 轻松反转。

Hope this helped!希望这有帮助!

That works fine for me:这对我来说很好用:

string[] characters = new string[] { ".", ",", "'" };
bool contains = characters.Any(c => word.Contains(c));

You could combine the strings with regex or statements, and then "do it in one pass," but technically the regex would still performing a loop internally.您可以将字符串与正则表达式或语句组合在一起,然后“一次性完成”,但从技术上讲,正则表达式仍会在内部执行循环。 Ultimately, looping is necessary.最终,循环是必要的。

If the "array" will never change (or change only infrequently), and you'll have many input strings that you're testing against it, then you could build a HashSet<string> from the array.如果“数组”永远不会更改(或仅很少更改),并且您将有许多要针对它进行测试的输入字符串,那么您可以从该数组构建一个HashSet<string> HashSet<T>.Contains is an O(1) operation, as opposed to a loop which is O(N). HashSet<T>.Contains是一个 O(1) 操作,而不是一个 O(N) 的循环。

But it would take some (small) amount of time to build the HashSet.但是构建 HashSet 需要一些(少量)时间。 If the array will change frequently, then a loop is the only realistic way to do it.如果数组会频繁更改,那么循环是唯一可行的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM