如何在字符串中查找包含短划线的字符串

Jon*_*han 0 c++ stl

我尝试使用此代码获取字符串"-a"的位置

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
string command("test –a string");
size_t pos = command.find("-a");
cout << "position found = " << pos << endl;
}
Run Code Online (Sandbox Code Playgroud)

这产生了这个输出:

position found = 4294967295
Run Code Online (Sandbox Code Playgroud)

如果我删除' - '它按预期工作.返回8.

das*_*ght 5

您获得string::npos返回的值,因为库认为它无法-a在字符串中找到.

这样做的原因是您在字符串中使用不同的短划线-,在搜索字符串中使用短划线.

在两个地方用正确的字符替换字符后,代码就会开始正常工作(演示).