Checking multiple contains on one string
Asked Answered
A

8

16

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?

Auspice answered 2/5, 2012 at 17:53 Comment(3)
similar to this question #195430Lamere
I saw that question, I was hoping I could find a easier solution since I know all the characters I'm searching for ahead of time (which I have thanks for all the answers!).Auspice
possible duplicate of VB.NET - Adding more than 1 string to .containsMaracaibo
A
31

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)
Altricial answered 2/5, 2012 at 17:55 Comment(0)
E
12

How about this?

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

    }
Eslinger answered 2/5, 2012 at 17:57 Comment(4)
Just one thing: IndexOfAny handles only single characters, it doesn't handle strings.Altricial
In the OP only single characters are checked for.Eslinger
of course, that was just a side note, because IndexOf actually has an overloaded version with string.Altricial
@Altricial nope msdn.microsoft.com/en-us/library/…Erotomania
T
8

Does this win for shortest?

@".,/\".Any(input.Contains)
Touchhole answered 2/5, 2012 at 18:4 Comment(0)
C
6
"asdfasdf".ContainsAny(".","/","4");

public static bool ContainsAny(this string stringToCheck, params string[] parameters)
{
    return parameters.Any(parameter => stringToCheck.Contains(parameter));
}
Charlena answered 11/4, 2014 at 18:55 Comment(2)
Doesn't work in C#. The type string does not contain a definition for "ContainsAny"Homeomorphism
I think, he is asking you to create your own method ContainsAny(arg1, arg2). He showed that as well.Gentianaceous
V
4

Try

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

or

If (input.IndexOfAny(@",/\.".ToCharArray()) >= 0) {
    ...
}
Viscometer answered 2/5, 2012 at 17:58 Comment(0)
B
4

You could use some Linq:

if ( ",/\\.".ToCharArray().Any( c => input.Contains( c ) ) )
Bowne answered 2/5, 2012 at 17:58 Comment(0)
M
4

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)
Materiel answered 2/5, 2012 at 17:59 Comment(0)
O
1

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
Optimal answered 29/8, 2019 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.