您的位置:首页 > 编程语言 > C语言/C++

C++ string类:find()和find_first_of()

2016-04-13 09:34 561 查看
容易搞混的两个函数,给出所有重载函数:

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在当前串中的位置

int find_first_of(char c, int pos = 0) const;//从pos开始查找字符c第一次出现的位置
int find_first_of(const char *s, int pos = 0) const; //从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置
int find_first_of(const char *s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;

共同点:

查找成功时返回所在位置,失败返回string::npos的值,string::npos一般是MAX_INT(即2^32
- 1)

差异:

find(): 查找字符串中第一次出现字符c、字符串s的位置;

find_first_of(): 查找字符串中字符c、字符数组s中任意一个字符第一次出现的位置。

例如:

string haystack = "helloworld";
string needle = "world";
cout << haystack.find_first_of(needle) << endl; //2, index of first 'l'
cout << haystack.find(needle) << endl; //5, index of first "world"

needle = "";
cout << haystack.find_first_of(needle) << endl;//string::npos, 因为字符数组s为空,haystack中找不到空字符(区别于'\0')
cout << haystack.find(needle) << endl;//0, 空串

类似的,还有rfind()和find_last_of(),以及find_first_not_of(), find_last_not_of().

参考文章:

http://blog.csdn.net/richard_123/article/details/18304181
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息