Thread: Comparing two strings

  1. #1
    Registered User eam's Avatar
    Join Date
    Oct 2003
    Posts
    53

    Comparing two strings

    I know how to compare two strings to see if they are exactly the same, but how can see if one is inside another?

    Example:
    Code:
    string word1 = "one";
    string word2 = "oneword";
    How can I make an if that checks if word2 has word1 in it?

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    You can use the find method:
    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string word1 = "one";
        std::string word2 = "oneword";
        if (word2.find(word1) != std::string::npos)
            std::cout << "Found it!" << std::endl;
    }

  3. #3
    Registered User eam's Avatar
    Join Date
    Oct 2003
    Posts
    53
    Thanks

    But if word2 is changed to "wordone" it doesn't work anymore, so I assume it has to be at the biginning of the other string. How can I get it to work both ways?
    Last edited by eam; 11-05-2003 at 01:51 AM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Originally posted by eam
    Thanks

    But if word2 is changed to "wordone" it doesn't work anymore, so I assume it has to be at the biginning of the other string. How can I get it to work both ways?
    Are you sure you didnt make a typo?
    It should still work.

  5. #5
    Registered User eam's Avatar
    Join Date
    Oct 2003
    Posts
    53
    I rewrote the file and now it works... I must have screwed something up last time (it was 4 am!!).

    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-29-2009, 10:13 AM
  2. Problem with comparing strings!
    By adrian2009 in forum C Programming
    Replies: 2
    Last Post: 02-28-2009, 10:44 PM
  3. comparing strings using argv
    By eth0 in forum C Programming
    Replies: 2
    Last Post: 09-20-2005, 09:20 AM
  4. comparing strings
    By infinitum in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2003, 12:10 PM
  5. Comparing Strings
    By Perica in forum C++ Programming
    Replies: 6
    Last Post: 02-12-2003, 11:41 PM