Reputation:
How would I look through a string for a word rather then each character in that word. I have my code here and it always seems to find everything that is .obj even if its o or b or j or "." I checked the docuementation here but was unable to find an answer. Here is my code:
string &str = *it;
if(it->find(".obj"))
{
cout << "Found .Obj" << endl;
}
I also tried to use string::compare
but that failed.
Upvotes: 0
Views: 87
Reputation: 1174
find
does search for the full text string that you pass as the function argument. What you're misunderstanding is the return value; find
doesn't return true or false for whether or not it found the string you requested; it returns the index in the string where it found your requested substring, or std::string::npos
if no match was found.
So for example:
std::string a = "foobar.obj";
std::string b = "baz.obj";
std::string c = "qux";
std::string d = ".obj";
a.find(".obj") == 6
b.find(".obj") == 3
c.find(".obj") == std::string::npos // not found
d.find(".obj") == 0
When interpreted as a boolean value, any integer other than 0 is treated as "true" -- even the "not found" std::string::npos value. Which is, I think, what has you confused.
So in your "if" statement, then, instead of:
if (it->find(".obj"))
You want to be testing:
if (it->find(".obj") != std::string::npos)
Upvotes: 8