I was wondering how you check if a certain string is in another string? Like say if you type "cats", how would you determine if "cat" was in that string?
I was wondering how you check if a certain string is in another string? Like say if you type "cats", how would you determine if "cat" was in that string?
Use the strstr function. If the substring is there, it will be returned as the return value, if it's not there, then it will return NULL
The string container offers a find member function that can be used to determine this:
Code:std::string str("cats"); if( str.find("cat") != std::string::npos ) { // Found substring "cat" in str } else { // Could not find substring "cat" in str. }
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Alternatively you can use the find algorithms. Take a look at http://www.cppreference.com/ for C++ strings and AlgorithmsCode:std::string myString = "Hello Nice World!"; std::string searchfor = "Nice"; std::size_t where; // starts search at position 0 and returns location where found where = myString.find(searchfor, 0);
Originally Posted by brewbuck:
Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.
Thanks that worked perfectly hk, mario's look's like it has the same idea, so thanks to you too mario.
Edit:Wait, how do you make it so it checks in multiple words? Like, say I type "the cat drinks milk", it is going to the else, it is not recognizing the string as having the word "cat" in it. Any suggestions?
Last edited by relyt_123; 07-26-2006 at 03:42 PM.
>> Alternatively you can use the find algorithms.
Don't use the find algorithm with string, since it has its own version that may be optimized for string's representation.
>> Any suggestions?
Show the code. Replacing std::string str("cats"); with std::string str("the cat drinks milk"); in hk_mp5kpdw's code should work.
Umm...well that's not what I meant. I meant if the user inputs "The cat drinks milk" it won't say that "cat" is in the string, because it is more than one word.
Show the code. If you're trying to say that your input function isn't working when the user enters more than one word, you probably need to use getline to read in the entire line.