I want to check if my string has two consecutive spaces in it. What's the easiest way to find out?
+5
A:
Use the find()
method of std::string
. It returns the special constant std::string::npos
if the value was not found, so this is easy to check for:
if (myString.find(" ") != std::string::npos)
{
cerr << "double spaces found!";
}
unwind
2010-02-26 13:11:16
Sorry, but what?
MeDiCS
2010-02-26 13:13:24
Oh, you aren't familiar with English++?
2010-02-26 14:28:41
If you're going to use `strstr`, you should use `str.c_str()`, because it takes a `char *`.
Javier Badia
2010-02-26 13:14:44
+1
A:
#include <string>
bool are_there_two_spaces(const std::string& s) {
if (s.find(" ") != std::string::npos) {
return true;
} else {
return false;
}
}
Javier Badia
2010-02-26 13:13:16
Why explicit returns of boolean values? If you want to have a function, consider just returning the result of the comparison directly. It's boolean by definition.
unwind
2010-02-26 13:25:34
`return (s.find(" ") != std::string::npos);` should do. However, this'll be optimized out I guess.
legends2k
2010-02-26 13:33:46
@unwind: I know that, but since the asker didn't know about this function, I tried to write the example as clearly as possible.
Javier Badia
2010-02-26 14:40:27
A:
string s = "foo bar";
int i = s.find(" ");
if(i != string::npos)
cout << "Found at: " << i << endl;
Martin Wickman
2010-02-26 13:13:19