如何查找字符串中包含破折号的字符串

How to find string that contain dash in a string

本文关键字:字符串 包含 破折号 何查找 查找      更新时间:2023-10-16

我尝试用这个代码获得字符串"-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;
}

产生如下输出:

position found = 4294967295

如果我删除'-',它的工作如预期。返回8。

返回string::npos值,因为库认为它在字符串中找不到-a

这样做的原因是您使用不同的破折号-在字符串中使用长破折号,在搜索字符串中使用短破折号-

一旦你在两个地方用正确的字符替换,你的代码开始正常工作(演示)。

表示有不同的第一个字符

您可以使用第一个字符并将它们放在语句

中进行检查。
std::cout << ( '–' == '-' ) << std::endl; 

由于它们是不同的函数find返回值std::string::npos,该值定义为std::string::size_type( -1 )或等于4294967295

如果你仔细看,你会发现'-'不是'-'。