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

时间:2016-06-20 02:31:51

标签: 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的{​​{1}}类型应该针对size_type

  • m的含义是什么意思?溢出?

2 个答案:

答案 0 :(得分:4)

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

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

  1. 如果字符串匹配,则返回第一个匹配的第一个字符的位置。
  2. 如果未找到匹配项,则返回string :: npos
  3. 其中 npos 是一个静态成员常量值,其值为 size_t (无符号整数类型)的元素的最大可能值。

    验证它是否打印字符串:: npos

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

答案 1 :(得分:1)

size_type本身不是一个类型,它是一个定义如下的别名:

typedef Allocator::size_type size_type; // until c++11
typedef std::allocator_traits<Allocator>::size_type size_type; // since c++11

由于您使用的是std::string,因此分配器为std::allocator<char>,因此size_typestd::size_t

std::type_info::name的返回值是实现定义的,m是您的编译器(可能是g ++)选择用于std::size_t的内容。

找不到子字符串时std::basic_string::find的返回值为std::basic_string::npos,定义为:

static const size_type npos = -1;

在您的情况下,它归结为:

static const std::size_t npos = -1;
// which is (due to arithmetic modulo 2^n):
static const std::size_t npos = std::numeric_limits<std::size_t>::max();

使用您的编译器,结果值为184467440737095516152^64 - 1因为std::size_t可能是您计算机上的64位值。这是可能的值std::size_t不需要是64位长。

您应该始终直接针对std::basic_string::find测试std::basic_string::npos(以及其他相关功能)的返回值。