我有一个程序,用于检查字符串中的子字符串。 程序:
#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 was not found
。
在这种情况下,find() 方法返回什么?
最佳答案
在空输入上按回车键不会在字符串中放入换行符。 std::getline
消耗换行符,所以你所有的子字符串都是空字符串。
根据 cppreference函数std::string::find
an empty substring is found at pos if and only if
pos <= size()
在你的例子中 pos
是0
因为你使用默认参数所以find
返回 0
.自 find
返回 0
你满足if条件。为防止这种情况,您可以检查一个空字符串,如
if(position != std::string::npos && !substr.empty())
关于c++ - 当 substring 只是一个换行符时,string.find(substring) 函数返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363906/