find 是STL模板库中提供的函数,主要用于字符串的操作

find 函数细分为几个不同功能的函数,这里将成对介绍

1.find()  /  rfind()

查找第一次出现的目标字符串:

void Find()
{
    string s1 = \"Iamleo\";
    string s2 = \"am\";
    int sub = s1.find(s2);
//  int sub = s1.find(\"am\");    //可以直接用字符串作为参数
    cout << sub << endl;        //find返回的是查找的字符串开头的下标,从0开始,此处返回的就是 1

}


void Find2()
{
    string s1 = \"Go to hell,Donald Trump!God damn you!\"
    int sub = s1.find(\"Trump\", 10);    //可以提供两个参数,第二个参数表示从下标多少开始查找,如果不给默认为 0
    cout << sub << endl;               //这里返回“Trump”的“T”的下标
    sub = s1.find(\"Trump\", 25);        //如果不在范围内,返回 -1
    cout << sub << endl;               //这里sub为 -1
}

rfind()find()的区别在于,rfind()是从后向前查找,仅此不同

2.find_first_of()  /  find_last_of()

作用和find()/rfind()差不多,只不过他是从指定位置开始找到第一个与子串中任意一个字符相等的字符

void Find()
{
    string s1 = \"Trump gonna screw up America!\";
    int sub = s1.find_first_of(\"up\");
    int sub2 = s1.find(\"up\");
    cout << \"sub= \" << sub << endl << \"sub1= \" << sub1 << endl;
}

结果

sub= 2
sub1= 18

同样是找“up”,返回结果却不一样,find()已经介绍过了,也可以理解

find_first_of() 则是在主字符串中找到第一个和子串中任意字符相同的位置,所以子串“up”被匹配到主串中的第一个“u”了,这就是区别,find()是全匹配,找到与给定子串完全相同的字符串的位置,find_first_of() 则是单一字符匹配

3.find_first_not_of()  /  find_last_not_of()

find_first_not_of()这个函数是查找第一个和子串不匹配的字符的位置

void Find()
{
    string s1 = \"Trump gonna screw up America!Damn you Trump!\"
    int sub = s1.find_first_not_of(\"Trump \");
    cout << sub << endl;   
}

需要注意的是,和上面find_first_of()  /  find_last_of()不同,find_first_not_of()  /  find_last_not_of()是全匹配,即匹配整个子串!

find_last_not_of()反向查找,有趣的是,子字符串可以反过来

void Find()
{
    string s1 = \"Trump gonna screw up America!Damn you Trump!\";
    int sub = s1.find_last_not_of(\"Trump\");
    cout << sub << endl;
    int sub2 = s1.find_last_not_of(\"pmurT\");
    cout << sub2 << endl;
}

结果是一样的,都会返回“you”和“Trump”中间的那个空格的下标,然而和他功能类似的 rfind() 却不可以这么用,字符串反写无法成功执行,返回 -1

收藏 打印