0
string str = "cat:fox";
string[] strArr = new string[] { "cat", "dog" };

I have a string like str. I need to check whether that string contains any element present in the strArr like exactly "cat" or "dog".

If the string is "cat:fox" method should returns true. If the string is "dog:fox" method should returns true.

The thing I tried was:

string[] split = str.Split(':');
blnReturn = false;

foreach (var item in split)
{
  foreach(var item1 in strArr)
  {
    if(item == item1)
       blnReturn = true;
  }
}

Note :- Meaning is values are concatenated with colon.I need to check whether that string contains any value present in the strArr.

How to do this better?

UPDATE

Requirement is if str is str = "cat dfgfg:fox"; It should not return true. Only it should be cat.

Otherwise we can check this way strData = str.Split(':'); and strArr is already there.

Condition is any one data in strArr (string array) should match with strData (string array) then it should return true.

1
  • 1
    What's wrong with this code you wrote? Commented Nov 12, 2013 at 8:04

8 Answers 8

3

Looks like you can use Enumerable.Any method like;

string str = "cat:dog";
string[] strArr = new string[] { "cat", "dog" };

if (strArr.Any(str.Contains))
{
  // Your string contains one the array values
}

Of course this works also cats, catss and cat:asdasd:dog becuase of the Contains definition.

You didn't mentioned but if you don't want to match string like cat:asdasd dog check out Marc Gravell's answer which looks the correct one.

Sign up to request clarification or add additional context in comments.

3 Comments

though that would match cats instead of matching only cat
that has edge-cases, though; should "cat:prairie dog" be a match? in your code it will; in the original code, it won't
@MarcGravell You are right. To be honest, I didn't look too much OP's code becuase he wants to get If the string is "cat:fox" method should returns true. If the string is "dog:fox" method should returns true.
2

If you want to distinguish between "cat" and "cats" you better do:

bool Match(string str, string[] strArr)
{
    return strArr.Intersect(str.Split(':')).Any();
}

2 Comments

Rather than .Count() > 0, use .Any(). The reason is that Count() requires that the entire list be enumerated whereas .Any() will stop as soon as one is found.
@JimMischel I updated my answer. I appreciate it if people think about performance when using Linq.
2

In most circumstances, the code you post is fine. If you need to minimize allocations (because it is a tight loop), so don't want to Split, you can use something like:

public static bool ContainsToken(string value, string token, char delimiter = ';')
{
    if (string.IsNullOrEmpty(token)) return false;
    if (string.IsNullOrEmpty(value)) return false;

    int lastIndex = -1, idx, endIndex = value.Length - token.Length, tokenLength = token.Length;
    while ((idx = value.IndexOf(token, lastIndex + 1)) > lastIndex)
    {
        lastIndex = idx;
        if ((idx == 0 || (value[idx - 1] == delimiter))
            && (idx == endIndex || (value[idx + tokenLength] == delimiter)))
        {
            return true;
        }
    }
    return false;
}

then something like:

static bool ContainsAnyOf(string value, string values)
{
    for(int i = 0 ; i < strArr.Length; i++)
    {
        if(ContainsToken(values, value, ':')) return true;
    }
    return false;
}

Comments

0

You can use LINQ:

bool contains = strArr.Any(pattern => str.Contains(pattern));

Comments

0

This should do the trick, you don't have to split the original string and create a double loop:

foreach(string s in array)
    if(word.Contains(s))
        return true;
return false;

In a method:

public bool ContainsItem(string word, string[] array)
{
    foreach(string s in array)
        if(word.Contains(s))
            return true;                
    return false;
}

//Usage:
var result = ContainsItem(str, strArr);

Or you can use the Enumerable Any() method:

var result = strArr.Any(s => str.Contains(s));

Comments

0

You could also use a List instead of an Array:

string str = "cat:fox";
List<String> animallist = new List<String>();

animallist.add("cat");
animallist.add("dog");

//Now you can check like

if(animallist.Contains("cat")){

   //do something

}

Comments

0
var str = "cat:fox";
var strArr = new[] { "cat", "dog" };

var result = strArr.ToList().Where(str.Contains);

First element of result will contain 'cat'

Comments

0

Your attempt is correct!


Though if you a have very large string separated by : and you want to perform look up operations quite frequently you can use dictionary since it's Contains method is O(1) and so is very fast!

var dictionary=str.Split(new char[]{':'})
                  .ToDictionary(x=>x,x=>"");
bool contains=strArr.Any(x=>dictionary.ContainsKey(x));//fast ops

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.