c++ - 使用 string::find 查看字符串中是否有两个空格,此代码中的错误?

标签 c++ string

我正在阅读 string manipulations in C++ .作者在那里提供了一段代码,用于测试字符串中是否有两个空格,

string text;
getline (cin, text);

string::size_type position = text.find (' ');
if (position != string::npos)
{
    if  (text.find (' ', position+1) != string::npos)
    {
       cout << "Contains at least two spaces!" << endl;
    }else
    {
       cout << "Contains less than two spaces!" << endl;
    }
}else
{
  cout << "Contains no spaces!" << endl;
}

作者声明上述代码中存在错误。但是我看不到它,代码对我来说看起来不错。我错过了什么吗?

最佳答案

该网站的作者错了,程序中没有错误。

他认为 find 的可选参数必须在 0 和 length-1 之间。如果是这种情况,那么如果第一个空格是字符串的最后一个字符,程序就会失败,因为 position 将是 length-1,因此 position+1 将是 length,超出该范围。

但实际上,如果 position 参数太高,它只会返回 string::npos。所以没有问题。

关于c++ - 使用 string::find 查看字符串中是否有两个空格,此代码中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385737/

相关文章:

c++ - 在NAryMatIterator中了解平面

c++ - 除了加密之外,还有什么方法可以防止访问文本文件吗?

c++ - 如何在C++中使用其构造函数初始化unique_ptrs的二维 vector ?

java - 在Java中仅在第一次出现时使用特殊符号分割字符串?

php - Postgres/PHP PDO::PDOStatement->bindParam() 到 character(1) 字段

jquery - 使用 JQuery 将 HTML 标记作为字符串返回

c - 使用 strtok() 函数时的内存分配

c++ - 使用 std::bitset 或相同大小的基本类型?

c++ - unique_ptr(std::nullptr_t) 和模板

string - 类型 "string"和 "func() string"之间有什么区别?