3 Answers3

2

If you're just looking to see if a longer string contains a specific shorter string, use String.Contains.

For your example:

string[] urlStrings = new string[] 
{
    @"http://www.vkeong.com/2011/food-drink/heng-bak-kut-teh-delights-taman-kepong/#comments"
    @"http://www.vkeong.com/2009/food-drink/sen-kee-duck-satay-taman-desa-jaya-kepong"
    @"http://www.vkeong.com/2008/food-drink/nasi-lemak-wai-sik-kai-kepong-baru/"
}

foreach(String url in urlStrings)
{
    if(url.Contains("nasi-lemak"))
    {
        //Your code to handle a match here.
    }
}
AllenG
  • 8,112
  • 29
  • 40
1

You want the String.IndexOf method.

foreach(string url in url_list)
{
    if(url.IndexOf("nasi-lemak") != -1)
    {
        // Found!
    }
}
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
  • 2
    I have to ask: why is this preferable to .Contains? – AllenG May 19 '11 at 15:52
  • @AllenG - maybe for this http://stackoverflow.com/questions/498686/net-is-string-contains-faster-than-string-indexof – Simon Mourier May 19 '11 at 17:09
  • Well, yes, it stands to reason that just finding the index is faster than finding the index and then verifying that the result isn't -1, but since that's exactly what this solution is doing anyway, I'm not seeing a difference. Not saying it's a bad solution, just looking for a reason that I'd do this instead of the native .Contains to see if a String contained a certain substring. – AllenG May 19 '11 at 17:18
  • It's just one possible solution. Readability-wise, yeah I'd probably go with `.Contains`. – Chris Eberle May 19 '11 at 18:28
1

Surely we also need a LINQ answer :)

var matches = urlStrings.Where(s => s.Contains("nasi-lemak"));

// or if you prefer query form. This is really the same as above
var matches2 = from url in urlStrings
               where url.Contains("nasi-lemak")
               select url;

// Now you can use matches or matches2 in a foreach loop
foreach (var matchingUrl in matches)
     DoStuff(matchingUrl);
Isak Savo
  • 34,957
  • 11
  • 60
  • 92