-
October 25th, 2010, 11:23 AM
#1
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!
-
October 25th, 2010, 11:29 AM
#2
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
-
October 25th, 2010, 11:35 AM
#3
Re: Comparing Strings
Originally Posted by badgerer
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|