C# Check if string contains any matches in a string array

怎甘沉沦 提交于 2020-01-23 04:50:14

问题


What would be the fastest way to check if a string contains any matches in a string array in C#? I can do it using a loop, but I think that would be too slow.


回答1:


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.




回答2:


Using 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".




回答3:


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.

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().

Hope this helped!




回答4:


That works fine for me:

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



回答5:


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<T>.Contains is an O(1) operation, as opposed to a loop which is O(N).

But it would take some (small) amount of time to build the HashSet. If the array will change frequently, then a loop is the only realistic way to do it.



来源:https://stackoverflow.com/questions/4191108/c-sharp-check-if-string-contains-any-matches-in-a-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!