我正在阅读 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/