C++查找字符串

find() 函数可以在字符串中查找子字符串中出现的位置。该函数有两个参数,第一个参数是待查找的子字符串,第二个参数是表示开始查找的位置,如果第二个参数不指名的话则默认从 0 开始查找,也即从字符串首开始查找。

【例 1】
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second third";
    string s2 = "second";
    int index = s1.find(s2,5);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}
函数最终返回的是子字符串出现在字符串中的起始下标。例 1 程序最终会在下标 6 处找到 s2 字符串。如果没有查找到子字符串,则会返回一个无穷大值 4294967295。

rfind() 函数与 find() 函数很类似,同样是在字符串中查找子字符串。不同的是,find() 函数是从第二个参数开始往后查找,而 rfind() 函数则是最多查找到第二个参数处,如果到了第二个参数所指定的下标还没有找到子字符串,则返回一个无穷大值 4294967295。

【例 2】
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second third";
    string s2 = "second";
    int index = s1.rfind(s2,6);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}
例2中,rfind() 函数第二个参数是 6,也就是说起始查找从 0 到 6,如果找到了则返回下标,否则返回一个无穷大。本例中刚好在下标 6 的时候找到了子字符串 s2,故而返回下标 6。

find_first_of() 函数是用于查找子字符串和字符串共同具有的字符在字符串中出现的位置。

【例 3】
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second second third";
    string s2 = "asecond";
    int index = s1.find_first_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}
本例中 s1 和 s2 共同具有的字符是 's',该字符在 s1 中首次出现的下标是 3,故查找结果返回 3。

而 find_first_not_of() 函数则相反,它查找的是在 s1 字符串但不在 s2 字符串中的首位字符的下标,如果查找不成功则返回无穷大。

【例 4】
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "secondasecondthird";
    string s2 = "asecond";
    int index = s1.find_first_not_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}
在本例中在 s1 但是不在 s2 中的首字符是 't',其所在下标为 13,故而返回下标 13。