【问题标题】:What does string::npos mean? [duplicate]string::npos 是什么意思? [复制]
【发布时间】:2011-07-03 01:07:27
【问题描述】:

以下语句是什么意思?

    string s="Joe Alan Smith"";
    cout << (s.find("Allen") == string::npos) << endl; 

【问题讨论】:

    标签: c++


    【解决方案1】:

    其实string::find()返回的是找到的字符串的位置,但是如果没有找到给定的字符串,则返回string::npos,其中npos表示没有位置

    npos 是一个无符号整数值,标准将其定义为-1(有符号表示),表示没有位置。

    //npos is unsigned, that is why cast is needed to make it signed!
    cout << (signed int) string::npos <<endl; 
    

    输出:

    -1

    见 Ideone:http://www.ideone.com/VRHUj

    【讨论】:

    • 该值不是实现定义的;标准规定它是string::size_type(-1)
    • @Mike:谢谢。在我的回答中提到了这一点!
    【解决方案2】:

    http://www.cplusplus.com/reference/string/string/npos/

    作为返回值,通常用于表示失败。

    换句话说,如果在给定的字符串s中找不到字符串'Allen',则打印出来。

    【讨论】:

      【解决方案3】:

      .find() 方法如果在搜索字符串中没有找到目标字符串,则返回 string::npos。它是一个整数,其值不能表示“找到”的索引值,通常为 -1。有效的索引值是一个 >= 0 的整数,它表示找到目标字符串的索引。

      【讨论】:

        猜你喜欢
        • 2011-04-19
        • 2013-07-13
        • 1970-01-01
        • 2013-12-23
        • 2012-09-08
        • 1970-01-01
        • 1970-01-01
        • 2011-05-07
        相关资源
        最近更新 更多