在 C++ 中,find 函数用于从前往后在一个 字符串 中,查找另一个字符串,而 rfind 函数,用于从后往前查找字符串,同样,如果查找到,则返回子串最后一次出现的位置,否则,返回 npos。
int n = s1.rfind(s2);
参数 | 描述 |
---|---|
s1 | 源字符串。 |
s2 | 要查找的子串。 |
如果找到,则返回子串 s2 在字符串 s1 中最后一次出现的的位置,即下标,否则,返回 npos。
我们使用了 rfind 函数,实现了在字符串 s1 中反向查找字符串 s2。
C++ rfind 函数反向查找字符串
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str1 = "I love HaiCoder and i learn C++ from HaiCoder";
int findIndex1 = str1.rfind("HaiCoder");
int findIndex2 = str1.find("haicoder");
cout << "findIndex1 = " << findIndex1 << ", findIndex2 = " << findIndex2 << endl;
}
程序运行后,控制台输出如下:
我们首先,定义了一个字符串 变量 str1,接着,我们使用了字符串的 rfind 函数,在 str1 中反向查找字符串 “HaiCoder”,并将结果赋值给变量 findIndex1。
最后,我们再次使用了 rfind 函数,在字符串 str1 中,反向查找字符串 haicoder,并将结果赋值给 findIndex2,结果,我们发现,变量 findIndex1 为 37,即,子串 HaiCoder 在字符串 str1 中最后一次出现的位置。
变量 findIndex2 为 -1,即,子串 haicoder 在字符串 str1 中未查找到。
我们可以使用反向查找字符串,判断字符串中是否包含子串
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str1 = "Hello HaiCoder";
string str2 = "HaiCoder";
string str3 = "World";
int n1,n2;
if ((n1 = str1.rfind(str2)) != string::npos)
{
cout << str1 << " containes " << str2 << endl;
}
else
{
cout << str1 << " not containes " << str2 << endl;
}
if ((n2 = str1.rfind(str3)) != string::npos)
{
cout << str1 << " containes " << str3 << endl;
}
else
{
cout << str1 << " not containes " << str3 << endl;
}
}
程序运行后,控制台输出如下:
我们可以将 rfind 函数的返回值与 string::npos 进行比较,如果相等,则代表没有找到,否则,代表找到。
在 C++ 中 rfind 函数,用于从后往前查找字符串,如果查找到,则返回子串最后一次出现的位置,否则,返回 npos。