此函数用于查找指定的子字符串。
find - 语法
str1.find(str2);
find - 参数
str - 要搜索的字符串。
pos - 它定义开始搜索的字符位置。
n - 要搜索的字符串中的字符数。
ch - 它定义要搜索的字符。
find - 返回值
它返回第一个匹配项的第一个字符的位置。
find - 例子1
让我们看一个简单的例子。
#include<iostream> using namespace std; int main() { string str= "java is the best programming language"; cout << str<< ; cout <<" Position of the programming word is :"; cout<< str.find("programming"); return 0; }
输出:
Java is the best programming language Position of the programming word is 17
find - 例子2
让我们看一个简单的例子,通过传递字符的位置作为参数。
#include<iostream> using namespace std; int main() { string str= "Mango is my favorite fruit"; cout << str<< ; cout<< " position of fruit is :"; cout<< str.find("fruit",12); return 0; }
输出:
Mango is my favorite fruit Position of fruit is 21
find - 例子3
让我们看一下找到单个字符的简单示例。
#include<iostream> using namespace std; int main() { string str = "learnfk"; cout << "String contains :" << str; cout<< "position of p is :" << str.find(p); return 0; }
输出:
String contains : learnfk
Position of p is 5