在 C++ 中,我们要在一个 字符串 中查找另一个子串中的任意一个 字符 第一次出现的位置,我们可以使用 find_first_of 函数。
如果找到,则返回子串中任一字符第一次出现的位置,否则,返回 npos。
int n = s1.find_first_of(s2);
参数 | 描述 |
---|---|
s1 | 源字符串。 |
s2 | 要查找的子串。 |
如果找到,则返回子串 s2 中字符在字符串 s1 中第一次一次出现的的位置,即下标,否则,返回 npos。
我们使用了 find_first_of 函数,实现了在字符串 s1 中查找字符串 s2 中任一字符第一次出现的位置。
使用 find_first_of 函数,查找子串中任一字符在字符串出现的位置
#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.find_first_of("evol");
int findIndex2 = str1.find_first_of("AO");
cout << "findIndex1 = " << findIndex1 << ", findIndex2 = " << findIndex2 << endl;
}
程序运行后,控制台输出如下:
我们首先,定义了一个字符串 变量 str1,接着,我们使用了字符串的 find_first_of 函数,在 str1 中查找字符串 “evol” 中的任意一个字符第一次在 str1 中出现的位置,并将结果赋值给变量 findIndex1。
最后,我们再次使用了 find_first_of 函数,在字符串 str1 中,查找字符串 “AO” 中的任意一个字符第一次在 str1 中出现的位置,并将结果赋值给变量 findIndex2。
结果,我们发现,变量 findIndex1 为 2,即,子串 evol 中的任意字符在字符串 str1 中第一次一次出现的位置,这里返回的 2,即返回了字符 l 在字符串 str1 中的下标。
变量 findIndex2 为 -1,即,子串 AO 的所有字符在字符串 str1 中都未查找到。
在 C++ 中,我们要在一个字符串中查找另一个子串中的任意一个字符第一次出现的位置,我们可以使用 find_first_of 函数。