简体   繁体   中英

How to check whether string contains specific string in c#

I want to check whether the string contains another string. For ex : I have 'program mangement' string in one list and 'computer program' string in another list. I want to return 'computer program' as a result. I have tried below things

List<string> strlist1 = new List<string>();
strlist1.Add("program mangement");
strlist1.Add("english language");

List<string> strlist2 = new List<string>();
strlist2.Add("computer program");
strlist2.Add("computer");
strlist2.Add("test");

foreach(var keys in strlist2)
{
  var result = strlist1.Where(x=>x.Contains(keys)).FirstOrDefault();     
  Console.WriteLine(result);     
 }

I want the result as 'Computer Program' as the program word contains in second list. But it is not returning any result. can anyone suggest how to return the desired result..

You need to check whether computer program analytics contains computer program :

foreach (var keys in strlist2)
{
     var result = strlist1.Where(x => keys.Contains(x)).FirstOrDefault();
     Console.WriteLine(result);
}

UPDATE:

If it is necessary to check whether word, not the whole sentence, contains in another array, then we can split sentence in array of words and check them:

foreach (var keyList2 in strlist2)
{
    foreach (var keyList1 in strlist1)
    {
         var splittedWords_1= keyList1.Split(' ');
         var splittedWords_2 = keyList2.Split(' ');
         bool containsValues = splittedWords_1.Any(s1 => splittedWords_2.Contains(s1));                    
         if (containsValues)
         {
              Console.WriteLine(keyList2);
         }                   
    }                
}

i hope this help

var found = false;
foreach (var s in strlist1)
{
    found = strlist2.Any(c => c.Contains(s));
    if (found) break;
}
Console.WriteLine(found.ToString());

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