C++中String类find函数与string::npos的含义

C++中String类find函数与string::npos的含义

前言

  • 问题:有两个字符串a、b, 现想判断a字符串是否包含b字符串,该如何设计程序?
  • 思路:此处需要用到string库中的find函数与npos参数。

string::npos参数:

npos 是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type 许多容器都提供这个东西。

取值由实现决定,一般是-1,这样做,就不会存在移植的问题了。

find函数:

find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,

那么返回值就一定是npos。所以不难想到用if判断语句来实现!

简单而言:如果存在包含关系find函数返回的就是主串与子串相匹配的下标,如果不存在包含关系就返回npos(一个常数,表示不存在)(s.find("abcdefg")==string::npos

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    vector<string> s;
    string temp;
    /*出现逗号
    int count = 0;*/
    while(cin>>temp){
        /*出现逗号
        if(temp.find(',') != string::npos)
            count++;*/
        s.push_back(temp);
        if(cin.get() == '\n')
            break;
    }
    cout << s.size();
    /*出现逗号
    cout << s.size()+count;*/
    return 0;
}
string s = "asdafsacfsaf";
cout << string::npos << endl;
cout << s.find('b');

18446744073709551615
18446744073709551615

string s = "asdafsacfsaf";
cout << string::npos << endl;
if (s.find('b') == -1)
    cout << "sss" << endl;
cout << s.find('b');
18446744073709551615
sss
18446744073709551615

也可以直接用-1进行比较判断是否查找成功!

加油!

感谢!

努力!