tags:

views:

166

answers:

6

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
A: 
Make search for "  " in the string.
Ashish
Sorry, but what?
MeDiCS
Oh, you aren't familiar with English++?
A: 

Using C:

#include <cstring>
...
addr = strstr (str, "  ");
...
MeDiCS
If you're going to use `strstr`, you should use `str.c_str()`, because it takes a `char *`.
Javier Badia
+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
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
`return (s.find(" ") != std::string::npos);` should do. However, this'll be optimized out I guess.
legends2k
@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
A: 
string s = "foo  bar";
int i = s.find("  ");
if(i != string::npos)
   cout << "Found at: " << i << endl;
Martin Wickman
+1  A: 

This one of Jon Skeet's fave topics: see this presentation

Jon Winstanley