Checking multiple contains on one string

前端 未结 8 1328
孤独总比滥情好
孤独总比滥情好 2020-12-19 01:33

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

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


        
相关标签:
8条回答
  • 2020-12-19 01:54

    How about this?

        if(input.IndexOfAny(new char[] { ',', '/', '\\', '.' })>=0)
        {
    
        }
    
    0 讨论(0)
  • 2020-12-19 01:54

    You could use some Linq:

    if ( ",/\\.".ToCharArray().Any( c => input.Contains( c ) ) )
    
    0 讨论(0)
  • 2020-12-19 01:56

    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)
    
    0 讨论(0)
  • 2020-12-19 01:56
    "asdfasdf".ContainsAny(".","/","4");
    
    public static bool ContainsAny(this string stringToCheck, params string[] parameters)
    {
        return parameters.Any(parameter => stringToCheck.Contains(parameter));
    }
    
    0 讨论(0)
  • 2020-12-19 02:07

    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
    
    0 讨论(0)
  • 2020-12-19 02:09

    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)
    
    0 讨论(0)
提交回复
热议问题