C++中的string的find()函数

string的find()函数用于找出字母在字符串中的位置。

find(str,position)

find()的两个参数:

str:是要找的元素

position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素。

可以不填第二个参数,默认从字符串的开头进行查找。

返回值为目标字符的位置,当没有找到目标字符时返回npos。

 

例1:找到目标字符的位置

string s = "hello world!";
cout << s.find("e") << endl;

结果为:1

 

例2:未找到目标字符

string s = "hello world!";
if (s.find("a") == s.npos) {
    cout << "404 not found" << endl;
}

结果为:404 not found

 

例3:指定查找位置

string s = "hello world!";
cout << s.find("l",5) << endl;

结果为:9

从空格开始(包含空格)的后半部分字符串中寻找字符"l",结果找到了world中的"l"在整个字符串中的位置

 

找到目标字符在字符串中第一次出现和最后一次出现的位置

例4:

string s = "hello world!";
cout << "first time occur in s:"<<s.find_first_of("l") << endl;
cout << "last time occur in s:" << s.find_last_of("l") << endl;

结果为:

first time occur in s:2
last time occur in s:9

 

反向查找:

例5:

string s = "hello world!";
cout << s.rfind("l") << endl;

结果为:9

即从后往前第一次出现"l"的位置

 

 

 

参考一下:https://www.cnblogs.com/wkfvawl/p/9429128.html

 

 
 
 
posted @ 2020-07-15 10:13  为红颜  阅读(1188)  评论(0编辑  收藏  举报