Find string in List C#

In this article we will discuss different ways to find or search a given element in the list.

std::list does not provide ant find[] or contains[] method. So, if we want to search for an element in list or check if an element exists in std::list,then we not to write some code for it i.e.

Logic Used to find a given element in list,

  • Iterate over all the elements of list
    • For each element check if this element is equal to given element

Suppose we have a list of strings i.e.

std::list listOfStrs = { "is", "of", "the", "Hi", "Hello", "from" };
Now if we want to check if the exists in this list or not. Lets see different ways to do this,
Advertisements

Searching an element in std::list using std::find[]

std::find

STL Provides an algorithm std::find[] i.e.

template InputIterator find [InputIterator first, InputIterator last, const T& val];
In std::find[] you can pass two iterators and a value. It will iterate all the elements between 2 given iterators and compare the given val with each one.
If any match is found, then it will immediatelyreturn that iterator, else it returns the iterator pointing to end of list.

Lets see how to find a string in std::list using std::find

// Create a list Iterator std::list::iterator it; // Fetch the iterator of element with value 'the' it = std::find[listOfStrs.begin[], listOfStrs.end[], "the"]; // Check if iterator points to end or not if[it != listOfStrs.end[]] std::cout

Chủ Đề