CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2010
    Posts
    20

    Comparing Strings

    Hi!

    I am making a program that prints off a list of words entered by the user, by storing the inputs in a vector then reproducing the words using a for() statement.

    Part of the assignment is to "bleep" out certain words (i.e. replace the word entered with "bleep").

    I planned to do this by putting the words to be "bleeped" into a vector (bad_words[]), then using an if() statement to replace the words with "bleep":

    Code:
    	for (int i = 0; i < words.size(); ++i)
    		if (words[i] == disliked1 || disliked2 || disliked3)
    			cout << "BLEEP" << endl;
    		else
    			cout << words[i] << endl;
    However, it would appear that C++ does not allow you to compare strings with ||. I recognise that I could simply run the if() statement three times to catch the three words, but obviously if there were 100 words, that approach would be onerous. So how do I check all the words in a vector using an if() statement to "bleep" those words?

    Thanks!

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Comparing Strings

    Well, you could use the std::find() algorithm to check if a given word is in the vector. However, that option will become inefficient as the number of words to be checked increases. For large numbers of censored words, you'd do better to use a std::set<std::string> or std::unordered_set<std::string> rather than a vector, because these have a find() method which is more efficient than the generic find() algorithm.

    And by the way, the arguments on either size of || must be boolean expressions, eg
    Code:
    words[i] == disliked1 || words[i] == disliked2

  3. #3
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Comparing Strings

    Quote Originally Posted by badgerer View Post
    However, it would appear that C++ does not allow you to compare strings with ||.
    No, fortunately C++ is not as vague as everyday talk. When you say "word[i] equals dislike1 or dislike2" you are leaving out a part. What you actually mean is: "word[i] equals dislike1 or it equals dislike2". Now, that is understandable for a compiler (using the proper syntax of course).
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured