C++ 字符串 find_first_of()函数
此函数用于查找指定字符的第一次出现位置。
语法
假设有字符串str1和str。语法如下:
str1.find_first_of(str);
参数
str: 包含要搜索的字符的字符串。
pos: 定义要开始搜索的位置。
n: 标识要搜索的字符的数量。
ch: 定义要搜索的字符。
返回值
返回搜索到的字符的位置。
示例1
看看简单的示例。
#include<iostream>
using namespace std;
int main()
{
string str1 = "Dancing is my favorite hobby";
cout << "String contains :"<< str1<< '\n';
cout <<"Position of the first occurrence of the string 'favorite' is " << str1.find_first_of("favorite");
return 0;
}
输出:
String contains : Dancing is my favorite hobby
Position of the first occurrence of the string favorite is 1
示例2
我们来看一个简单的示例,其中指定了要开始搜索的位置。
#include<iostream>
using namespace std;
int main()
{
string str = "Welcome to the programming world";
cout<< "String contains : "<< str <<'\n';
cout<<"Now, start the search from the second position and we find the first occurrence of the 'programming' is :"<<str.find_first_of("programming",2);
return 0;
}
输出:
String contains : Welcome to the programming world
Now, start the search from the second position and we find the first occurrence of the 'programming' is : 4
示例3
让我们看一个简单的示例,找到单个字符第一次出现的位置。
#include<iostream>
using namespace std;
int main()
{
string str = "javatpoint tutorial";
cout << "String contains :" << str<< '\n';
cout <<"Position of the first occurrence of 'a' character is :" << str.find_first_of('a');
return 0;
}
输出:
String contains javatpoint tutorial
Position of the first occurrence of 'a' character is : 1