关于C++中string类的查找函数的说明

来源:互联网 发布:域名主机名是什么 编辑:程序博客网 时间:2024/04/27 21:53

string类的查找函数:

int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置,如果入参pos没有指定,则默认从头查找。
//查找成功时返回所在位置,即要查找的字符或者字符串的第一个字符在长字符串中的下标,如果失败返回string::npos的值

在C++中常量npos是这样定义的:

static const size_t npos = -1;


测试程序:
#include<iostream>#include<string>using namespace std;int main(){string longstring = "123456789";string shortstring = "C++";int result = longstring.find(shortstring);size_t result2 = longstring.find(shortstring);cout<<result<<endl;//如果查找不到输出-1,如果查找到输出shortstring的第一个字符在longstring中的下标。如果想把查找后的返回值用于判断,可用result >= 0cout<<result2<<endl;//如果查找不到输出4294967295,因为result2是无符号整数类型。如果想把查找后的返回值用于判断,最好用result2 != string::nposif(result >= 0)cout<<"Find!"<<endl;elsecout<<"Can't find!"<<endl;if(result2 != string::npos)cout<<"Find!"<<endl;elsecout<<"Can't find!"<<endl;return 0;}


0 0