string类的find()函数

头文件

#include < string >

函数原型及使用范例

/*
用法:find(str,pos)
str:是要找的元素
position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素。(不写默认从字符串开始处查找)
找不到时返回str.npos
*/
//范例:(找得到)
string s = "hello world!";
cout << s.find("e") << endl;
//输出1
//范例:(找不到)
string s = "hello world!";
if (s.find("a") == s.npos) {
    cout << "Not Found" << endl;
}
//输出not found

扩展

s.rfind(str,pos)
//反向查找,返回索引
//查找第一个出现的位置
s.find_first_of(str,pos)
//查找最后一个出现的位置
s.find_last_of(str,pos)
发布了45 篇原创文章 · 获赞 0 · 访问量 993

猜你喜欢

转载自blog.csdn.net/qq_41985293/article/details/104158468