C# 找到匹配的单词C

C# 找到匹配的单词C,c#,string-matching,C#,String Matching,我有3个字符串,我想找到匹配项 你想要这个方法 如果您只是想看看长字符串是否包含特定的短字符串,请使用string.contains 例如: 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/s

我有3个字符串,我想找到匹配项

你想要这个方法


如果您只是想看看长字符串是否包含特定的短字符串,请使用string.contains

例如:

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

当然,我们也需要一个LINQ答案:

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

我不得不问:为什么这比.Contains更可取?@AllenG-也许出于这个原因,是的,找到索引比找到索引然后验证结果不是-1要快得多,但既然这正是这个解决方案所做的,我看不出有什么不同。不是说这是一个糟糕的解决方案,只是寻找一个原因,我会这样做,而不是本机的。包含,看看字符串是否包含某个子字符串。这只是一个可能的解决方案。就可读性而言,是的,我可能会选择.Contains。在本例中,我的首选项是第一个
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.
    }
}
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);