C++ 当子字符串位于开头时,std::string::find无法按预期工作

C++ 当子字符串位于开头时,std::string::find无法按预期工作,c++,string,stl,C++,String,Stl,由于某些原因,当我搜索的子字符串位于字符串的开头时,返回std::string:npos const char delim[] = {'H', 'E', 'L', 'L'}; std::string::size_type pos = 0; std::string bigString = "HELLO"; while(pos != std::string::npos) { pos = bigString.find(delim, pos); ... } 指定的pos应该是包含的

由于某些原因,当我搜索的子字符串位于字符串的开头时,返回std::string:npos

const char delim[] = {'H', 'E', 'L', 'L'};

std::string::size_type pos = 0;
std::string bigString = "HELLO";

while(pos != std::string::npos)
{
    pos = bigString.find(delim, pos);
    ...
}
指定的pos应该是包含的,但如果为0,则不是包含的,并且函数返回NPO。但是,如果我指定要搜索的字符串的大小,它就可以工作

pos = bigString.find(delim, pos, 4);

这种行为的原因是什么?

您正在使用的
std::string::find
重载需要以空结尾的字符串,因此

const char delim[] = {'H', 'E', 'L', 'L', '\0'};

您使用的成员函数find的形式不正确,属于类std::basic_string。由于搜索的字符串delim没有终止的零字符,因此必须明确指定要查找的字符数。否则,字符串的大小将计算不正确,并且程序的行为未定义。因此,请使用以下形式的查找

size_type find(const charT* s, size_type pos, size_type n) const;
您的代码将如下所示

const char delim[] = {'H', 'E', 'L', 'L'};

std::string::size_type pos = 0;
std::string bigString = "HELLO";

while(pos != std::string::npos)
{
    pos = bigString.find( delim, pos, sizeof( delim ) );
    ...
}

您忘记了0-终止您的
delim
。这个问题似乎离题了,因为它很琐碎。@H2CO3适用于大多数SO问题:)@juanchopanza确实…:/终止字符串!或者只是
const char delim[]=“地狱”