zoukankan      html  css  js  c++  java
  • std::string::find() 和 std::string::npos

    npos是一个常数,用来表示不存在的位置,string::npos代表字符串到头了结束了。
     
    int idx = str.find("abc");
    if (idx == string::npos)
      ...
     
    上述代码中,idx的类型被定义为int,这是错误的,即使定义为 unsigned int 也是错的,它必须定义为 string::size_type。
     
    npos 是这样定义的:
    static const size_type npos = -1;
     
    因为 string::size_type (由字符串配置器 allocator 定义) 描述的是 size,故需为无符号整数型别。因为缺省配置器以型别 size_t 作为 size_type,于是 -1 被转换为无符号整数型别,npos 也就成了该型别的最大无符号值。不过实际数值还是取决于型别 size_type 的实际定义。不幸的是这些最大值都不相同。事实上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是两者型别大小不同)。因此,比较式 idx == string::npos 中,如果 idx 的值为-1,由于 idx 和字符串string::npos 型别不同,比较结果可能得到 false。
     
    要想判断 find() 的结果是否为npos,最好的办法是直接比较:
    if (str.find("abc") == string::npos) { ... }
     
    (EOF)
  • 相关阅读:
    Python如何爬取淘宝MM呢?教你一招
    Python爬虫实战之如何爬取百度贴吧帖子?案例详解
    SpringBoot定时任务如何正确运用?案例详解
    JS数组之重排序方法
    JS数组之栈和队列
    JS数组之转换方法
    计算机相关推荐教程
    多维数组
    重新认识变量和数组
    数组
  • 原文地址:https://www.cnblogs.com/shmilxu/p/4837660.html
Copyright © 2011-2022 走看看