This tutorial will discuss about a unique way to check if array contains a specific string in C++.
Suppose we have a string array, and a string value. Like this,
const char* arr[] = {"This", "is", "a", "sample", "text", "message"}; std::string strvalue = "sample";
Now, we want to check if this string array arr
contains a specific string strvalue
or not.
For that we are going to use STL algorithm std::find()
. Like this,
// Search for the string in string array auto it = std::find( std::begin(arr), std::end(arr), strvalue) ; // Checkif iterator is valid if(it != std::end(arr)) { std::cout << "Yes, Array contains the specified string n"; }
We passed three arguments in the std::find()
function,
Frequently Asked:
- First arguments is iterator pointing to the start of array
arr
. - Second arguments is iterator pointing to the end of array
arr
. - The third argument is the string value ‘strvalue’.
It returns an iterator pointing to the first occurrence of the string strvalue
in the array arr
. Whereas, if the string value does not exist in the array then it will return an iterator pointing to the end of the array arr
.
Now after the function std::find()
returns an iterator, we need check if the iterator is valid or not. It means we need to make sure that iterator is not equal to the end of the array. If not, then it means array contains the specified string.
Let’s see the complete example,
#include <iostream> #include <algorithm> #include <string> int main() { // An array of strings const char* arr[] = {"This", "is", "a", "sample", "text", "message"}; std::string strvalue = "sample"; // Search for the string in string array auto it = std::find( std::begin(arr), std::end(arr), strvalue) ; // Checkif iterator is valid if(it != std::end(arr)) { std::cout << "Yes, Array contains the specified string n"; } else { std::cout << "No, Array does not contains the specified string n"; } return 0; }
Output :
Yes, Array contains the specified string
Summary
Today we learned about a way to check if array contains a specific string in C++. Thanks.
Leave a Reply
You must be logged in to post a comment.