Compare 2 std::string in c++ virtual studio 2015
Hey, I'm trying to compare a std::string with a string out of an array. Somehow it doesn't work.
The User types in a word in the main method and it gets delivered to my search method as keyword.
in the search function i have my stringarray with words. If my keyword matches with one of the words in the array, the method shall return true; else false.
Code:
bool serach(string keyword){
bool found = false;
int index;
//Archive//
string words[] = { "msg", "chrome","steam","spotify","discord" };
//-----// Searching for Input //-----//
for (int i = 0; i < sizeof(words); i++) {
if (words[i] == keyword) {
cout << "found";
getchar();
return true;
}
if (!found == false && i == sizeof(words)) {
return false;
}
}
Re: Compare 2 std::string in c++ virtual studio 2015
Code:
if (!found == false && i == sizeof(words))
Within the for loop, i will never be equal to sizeof(words) as the for loop comparison test will fail and the loop will exit. Why have this test at all? If the loop exits normally then the word hasn't been found so just return false after the loop.
Re: Compare 2 std::string in c++ virtual studio 2015
You can actually shorten this code by using an STL algorithm function. Consider
Code:
bool search(string keyword) {
const string words[] = { "msg", "chrome","steam","spotify","discord" };
return find(begin(words), end(words), keyword) != end(words);
}
Re: Compare 2 std::string in c++ virtual studio 2015
Thank you very much. It worked ^^ Could you please explain to me what the != end(works) exactly does to the find function?
Re: Compare 2 std::string in c++ virtual studio 2015
If find() doesn't find the requested string, it returns the passed 2nd argument to find() - in this case end(words). So if the string is found, then the returned value is not end(words) and so the comparison test for not equal is true and so true is returned. If the comparison test for not equal is false, the string hasn't been found and so false is returned. See http://www.cplusplus.com/reference/algorithm/find/
Re: Compare 2 std::string in c++ virtual studio 2015