I want to che开发者_开发技巧ck if my string has two consecutive spaces in it. What's the easiest way to find out?
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!";
}
#include <string>
bool are_there_two_spaces(const std::string& s) {
if (s.find(" ") != std::string::npos) {
return true;
} else {
return false;
}
}
This one of Jon Skeet's fave topics: see this presentation
Make search for " " in the string.
Using C:
#include <cstring>
...
addr = strstr (str, " ");
...
string s = "foo bar";
int i = s.find(" ");
if(i != string::npos)
cout << "Found at: " << i << endl;
精彩评论