Checking multiple contains on one string

筅森魡賤 提交于 2019-12-06 23:55:26

问题


So I have a conditional that currently looks like this...

if (input.Contains(",") || input.Contains("/") || input.Contains(@"\") || input.Contains("."))

I need to add a few more characters that I want to check for and was wondering if there's a more condensed syntax to accomplish the same thing? Something similar to SQL's IN operator?

if ( input IN (",", "/", @"\", ....etc )  )

Anybody know of any cool tricks to accomplish this without adding lots of code?


回答1:


Consider using Regex (specify characters you want to check in brackets - remember that some of them must be escaped):

Regex.IsMatch(input, @"[,/]");

or

new[] {",", "/"}.Any(input.Contains)



回答2:


How about this?

    if(input.IndexOfAny(new char[] { ',', '/', '\\', '.' })>=0)
    {

    }



回答3:


Does this win for shortest?

@".,/\".Any(input.Contains)



回答4:


You could use some Linq:

if ( ",/\\.".ToCharArray().Any( c => input.Contains( c ) ) )



回答5:


"asdfasdf".ContainsAny(".","/","4");

public static bool ContainsAny(this string stringToCheck, params string[] parameters)
{
    return parameters.Any(parameter => stringToCheck.Contains(parameter));
}



回答6:


You could use String.IndexOfAny -- it will scan the string for any one of a set of characters in an array:

if (e.Label.IndexOfAny(new char[]{',', '/', @'\', '.' /* other chars here */}) > -1)



回答7:


Try

If (input.IndexOfAny(new char[] { ',', '/', '\\', '.' }) >= 0) {
    ...
}

or

If (input.IndexOfAny(@",/\.".ToCharArray()) >= 0) {
    ...
}



回答8:


An extension method could make things look clean. Have a look at the following.

 public static bool ContainsChar(this string input, params char[] characters)
        {
            foreach (var character in characters)
            {
                if (input.Contains(character))
                {
                    return true;
                }
            }
            return false;
        }

The method's parameters are variadic, so you can add as many chars as you want separated by commas. If you're not comfortable using extension methods, modify to the following:

public static bool ContainsChar(string input, params char[] characters)
            {
                foreach (var character in characters)
                {
                    if (input.Contains(character))
                    {
                        return true;
                    }
                }
                return false;
            }

Example usage follows:

string myString = "this is my string";
//extension
if (myString.ContainsChar('.', '*', '%')) //do something

//static method
if (ContainsChar(myString, '.', '*', '%')) //do something


来源:https://stackoverflow.com/questions/10419106/checking-multiple-contains-on-one-string

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