>我有一个程序,用于检查子字符串是否为字符串。程序:
#include<iostream>
#include<cstring>
int main()
{
std::string str, substr;
std::cout<<"n Enter a string : ";
std::getline(std::cin, str);
std::cout<<"n Enter a possible substring of the string : ";
std::getline(std::cin, substr);
std::size_t position = str.find(substr);
if(position != std::string::npos)
std::cout<<substr<<" was found at position "<<position<<std::endl;
else
std::cout<<"n The substring you entered wasn't found n";
return 0;
}
我有一个输入,它没有给出正确的输出。例:
Enter a string : Stackoverflow
Enter a possible substring of the string :
was found at position 0
输入子字符串时,我只需按回车键。所以输出应该是The substring you entered wasn't found
.在这种情况下,find() 方法返回什么?
对空输入按 Enter 不会在字符串中放置换行符。 std::getline
使用换行符,因此子字符串的空字符串中的所有内容。
根据 cpp首选项,函数 std::string::find
在 POS 中找到空子字符串当且仅当
pos <= size()
在您的示例中,pos
在使用默认参数时0
,因此find
返回0
。 由于find
返回0
因此您满足 if 条件。 为了防止这种情况,您可以检查空字符串,例如
if(position != std::string::npos && !substr.empty())
std::getline()
函数在返回的字符串中不包含换行符,因此如果您只按 Enter 键,它将返回一个空字符串。空字符串位于任何字符串中。
在执行搜索之前,添加代码以验证substr
是否为非空。
问题是,通过输入一个新行,你基本上什么都不搜索,即 ""
. ""
立即找到(在字符串的开头),所以position
0
,而不是-1
(std::string::npos
)。换行符不由 std::getline 检索。
根据 cplusplus - .find() 函数返回
第一个匹配项的第一个字符的位置。
当您按下回车按钮时,std::getline() 会接受一个空字符串,并且每个字符串中都有一个空字符串。所以它返回位置 0(字符串的开头)。
您可以检查子字符串是否为空以避免这种情况。