简体   繁体   中英

Find the matching word C#

I have 3 strings, i would like find matches

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/

for each link above=="nasi-lemak"
{
  found!
}

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.
    }
}

You want the String.IndexOf method.

foreach(string url in url_list)
{
    if(url.IndexOf("nasi-lemak") != -1)
    {
        // Found!
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM