zoukankan      html  css  js  c++  java
  • std::string find 的返回值

    std::string  的方法 find,返回值类型是std::string::size_type, 对应的是查找对象在字符串中的位置(从0开始),

    如果未查找到,该返回值是一个很大的数据(4294967295),判断时与 std::string::npos 进行对比

    std::string str("abcdefg");
    std::string::size_type pos = str.find("abc");
    if (pos != std::string::npos)
    {
        cout << "Not find" << endl;
    }

    std::string str("abcdefg");
    if (str.find("abc") != std::string::npos)
    {
        cout << "Not find" << endl;
    }

    很多同学由于经常使用 CString 的缘故,喜欢这样写

    std::string str("abcdefg");
    int pos = str.find("abc");
    if (pos < 0)
    {
        cout << "Not find" << endl;
    }

    这样写理论上也是可以的,因为 size_type 相当于 unsigned int类型,最大值4294967295强制转换为int型,就是-1

    但下面的写法是错误的:

    std::string str("abcdefg");
    if (str.find("abc") < 0)  //错误,应该写成  != std::string::npos
    {
        cout << "Not find" << endl;
    }


    最后,建议使用size_type,这样可以适应不同的平台。因为int 类型的大小会根据不同平台而不同。


    拓展:
    s.find(s2)        第一次出现的位置
    s.rfind           最后一次出现的位置
    s.find_first_of(s2)    任何一个字符第一次出现的位置
    s.find_last_of         任何一个字符最后一次出现的位置
    s.find_first_not_of(s2)   第一个不在s2中的字符所在位置
    s.find_last_not_of(s2)    最后一个不在s2中的字符所在位置

    《完》


  • 相关阅读:
    关于加密程序
    C++11的新特性lambda的小试牛刀RAII
    自动生成makefile的脚本
    关于pcre正则表达式库libpcre
    利用PHP执行SQL文件,将SQL文件导入到数据库
    Linux 系统是否适合于您?
    一个少年电脑病毒作者的独白
    PHP编程效率的20个要点
    JVM源码分析之javaagent原理完全解读
    如何更好的利用Node.js的性能极限
  • 原文地址:https://www.cnblogs.com/pjl1119/p/8676647.html
Copyright © 2011-2022 走看看