c++ - 使用 std::string::find 在较小的字符串中查找较长的字符串

标签 c++ string

来自这段代码:

#include <iostream>
#include <typeinfo>
#include <string>

int main() {
    std::string const s = "Thisisastring";
    std::string const ss = "Thisisastringg";
    std::string const sss = "Thisisastrin";
    auto p = ss.find(s);
    std::cout << "p:" << typeid(p).name() << "\np =" << p << std::endl;
    auto pp = sss.find(s);
    std::cout << "pp:" << typeid(pp).name() << "\npp =" << pp << std::endl;
    return 0;
}

我得到以下输出:

p:m
p =0
pp:m
pp =18446744073709551615

问题:

  • 来自 this link , p 应该有类型 size_type 而不是 m?

  • pp 的值是什么意思?溢出?

最佳答案

pp 的值等于 string::npos (2^64-1 = 18446744073709551615)。即没有找到字符串,不是溢出

string.find(...) 方法返回以下任何内容

  1. 如果匹配到字符串,则返回第一个匹配的第一个字符的位置。
  2. 如果没有找到匹配项,则返回 string::npos

其中 npos 是一个静态成员常量值,对于类型为 size_t(无符号整数类型)的元素具有最大可能值。

为了验证它打印字符串::npos

std::cout << std::string::npos << std::endl;

关于c++ - 使用 std::string::find 在较小的字符串中查找较长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37913893/

相关文章:

ruby - Ruby 缺少的 string#unshift 最地道的替代品是什么?

c# - 在 C# 中比较日语字符

c++ - 使 CNG 加密 API 在 Windows XP 上工作?

c++ - 复制和修改 std::strings 时无法解释的差异

c++ - 在 MFC C++ 中查找 Indexof

java - 如何使用通配符搜索字符串数组

c++ - 我可以在 Visual C++ 2010 中使用不同颜色的注释吗?

c++ - 如何使用友元函数在模板类之外重载运算符==?

python - 类型错误 : Format Requires Mapping

java - 如何从数组列表中提取某些子字符串之间的不同子字符串?