c++ - 如何在字符串中查找包含破折号的字符串

标签 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;
}

这会产生这样的输出:

position found = 4294967295

如果我删除“-”,它会按预期工作。返回 8。

最佳答案

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

这是因为您在字符串中使用了不同的破折号,长破折号 和搜索字符串中的短破折号 -

一旦您在两个地方都用正确的字符替换了字符,您的代码就会开始正常工作 ( demo )。

关于c++ - 如何在字符串中查找包含破折号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23637647/

相关文章:

C++ 流引用作为类成员

c++ - 有没有办法在 C++ 中延迟初始化成员变量(类)?

c++ - 为什么 map 会比 unordered_map 快得多?

C++ STL : Custom sorting one vector based on contents of another

c++ - Apache qpid setDelay

c++ - 如何计算(A*B)%C?

c++ - DirectX 中的 vector 处理项目符号

c++ - 标准::原子 | compare_exchange_weak 与 compare_exchange_strong

c++ - memcmp 排序

c++ - 在一行中使用两个折叠表达式