Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a string in a list of strings in c#

Tags:

string

c#

list

I am trying to find if a list of strings contains a specific string in C#. for example: Suppose I have 3 entries in my list

list<string> s1 = new List<string>(){
  "the lazy boy went to the market in a car", 
  "tom", 
  "balloon"};
string s2 = "market";

Now I want to return true if s1 contains s2, which it does in this case.

return s1.Contains(s2);

This returns false which is not what I want. I was reading about Predicate but could not make much sense out of it for this case. Thanks in advance.

like image 687
vsg Avatar asked Dec 19 '14 22:12

vsg


People also ask

How do I find a string in an array of strings?

A simple solution is to linearly search given str in array of strings. A better solution is to do modified Binary Search. Like normal binary search, we compare given str with middle string. If middle string is empty, we find the closest non-empty string x (by linearly searching on both sides).

How do I find a word in a string in C?

Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.

How do you check if a string contains a substring in C?

Check if String contains Substring in C Language To check if a string contains given substring, iterate over the indices of this string and check if there is match with the substring from this index of the string in each iteration. If there is a match, then the substring is present in this string.

How do you check if a string is present in an array in C?

To check if given Array contains a specified element in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.


1 Answers

The simplest way is to search each string individually:

bool exists = s1.Any(s => s.Contains(s2));

The List<string>.Contains() method is going to check if any whole string matches the string you ask for. You need to check each individual list element to accomplish what you want.

Note that this may be a time-consuming operation, if your list has a large number of elements in it, very long strings, and especially in the case where the string you're searching for either does not exist or is found only near the end of the list.

like image 71
Peter Duniho Avatar answered Sep 23 '22 03:09

Peter Duniho