如何在字符串中查找两个连续空格的位置

时间:2010-02-26 13:09:40

标签: c++ string

我想检查我的字符串中是否有两个连续的空格。找出最简单的方法是什么?

6 个答案:

答案 0 :(得分:6)

使用find()的{​​{1}}方法。如果找不到值,它将返回特殊常量std::string,因此很容易检查:

std::string::npos

答案 1 :(得分:1)

#include <string>

bool are_there_two_spaces(const std::string& s) {
    if (s.find("  ") != std::string::npos) {
        return true;
    } else {
        return false;
    }
}

答案 2 :(得分:1)

这是Jon Skeet最喜欢的主题之一:see this presentation

答案 3 :(得分:0)

Make search for "  " in the string.

答案 4 :(得分:0)

使用C:

#include <cstring>
...
addr = strstr (str, "  ");
...

答案 5 :(得分:0)

string s = "foo  bar";
int i = s.find("  ");
if(i != string::npos)
   cout << "Found at: " << i << endl;