6.5C++查找字符串

参考:http://www.weixueyuan.net/view/6394.html

总结:

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

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

    注意:rfind函数是查到第二个参数,而不是字符串取到第2个参数,然后从此子字符串中查找,具体见例子。

        例2中rfind函数第二个参数是6,也就是说起始查找从0到6,如果找到了则返回下标,否则返回一个无穷大。本例中刚好在下标6的时候找到了子字符串s2,故而返回下标6。

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

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

    

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。 

原文地址:https://www.cnblogs.com/yongpan/p/7920165.html