If string contains the word "x" do something?

Hello
How can i make an if with a text detection? i want to do something like- if the string contains the word "text" do something-
how do i do that?
Thanks.and please don't use very advanced stuff.i mean c++ not C or other complicated things
closed account (j3Rz8vqX)
You're on the right track with using an conditional branch - If statement.
http://www.learncpp.com/cpp-tutorial/52-if-statements/

Now you may to browse the available methods in the string class; part of the standard library.
http://www.cplusplus.com/reference/string/string/

And possibly check the methods in the String operations section.

---
Spoiler:
http://www.cplusplus.com/reference/string/string/find/
and if no string is found, it returns this:
http://www.cplusplus.com/reference/string/string/npos/

Have fun.
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()    
{
    string word=;//declare string
    //prompt user for entry
    cout<<"Please enter a word: ";
    cin>>word;//assign user entry to string
    
    if (word=="text")
        //do something
    else
        //do something else
    return 0;//terminate program
}
closed account (j3Rz8vqX)
That certainly works for exact matches, but I believe hes looking for
if the string contains the word "text" do something

Sure, we could always change line 8 to something like this:
if (word=="test" || word=="TEST")
Or, we could convert the string to all upper or lower case before checking.
Last edited on
That doesn't fix the problem though. "This string contains some text." contains text but is not anywhere near == to "text".
Good point, I had missed the fact that the OP wanted to scan for the word test within the string, as opposed to checking for the word alone.
Last edited on
CplusplusAcolyte wrote:
Good point, I had missed the fact that the OP wanted to scan for the word test within the string, as opposed to checking for the word alone.
"checking for the word alone" has the same meaning as "to scan for the word [...] within the string". ;)
I think you know what I meant. I thought he was merely checking that the string contained "test" by itself, not checking for the presence of "test" within a string that may also contain other characters.
Last edited on
You used the word "contained", which again means the same as what you compared to.
Last edited on
I suppose I should have been clearer, then. I meant contained alone vs contained.
Rather than the ambiguous phrase "contained alone", consider "only contained". I normally would not push something like this so far but it is clear from this thread that a misuse of words can cause excessive confusion. Now we can avoid confusion in the future :)
Fair enough LB. I don't consider it nitpicking considering you often are attempting to answer questions I have, so if anything can help avoid confusion, it's to the good.
Topic archived. No new replies allowed.