gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:48:32 40 4
gpt4 key购买 nike

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

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com