find()函数笔记

 C++ find函数详解_c++ find-优快云博客  来自这里(仅仅笔记自用)

C++中的find()函数有多种用法。它可以用于string类,用于查找字符或字符串。查找成功则返回第一个字符或者字串的位置,查找失败则返回string::npos即为-1。此外,find()也可以用于vector容器,用于查询指定元素是否存在。还有一个STL函数find(),它位于<algorithm>头文件下,返回一个迭代器,指向范围内搜索元素的第一次出现。

#include <algorithm>
#include <vector>
#include <iostream>
 
int main()
{
    std::vector<int> v = {1, 2, 3, 4, 5};
    auto it = std::find(v.begin(), v.end(), 3);
    if (it != v.end())
        std::cout << "Element found: " << *it << '\n';
    else
        std::cout << "Element not found\n";
}
//上面的代码会在控制台输出“Element found: 3”。
<algorithm>下的find函数用于查找string类中的字符

它的用法与在其他容器中查找元素类似,只需将查找范围指定为字符串的起始和结尾即可。

下面这段代码演示了如何在一个字符串中查找指定字符:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
int main()
{
    string str = "Hello, world!";
    auto it = find(str.begin(), str.end(), 'w');
    if (it != str.end())
        cout << distance(str.begin(), it) << '\n'; // 输出7
    else
        cout << "Not found\n";
}
//上面的代码会在控制台输出“7”。

下面这段代码展示了如何使用search函数在一个string对象中查找子字符串"orld":

#include <iostream>
#include <string>
 
int main()
{
    std::string str = "Hello, world!";
    std::cout << str.find("world") << '\n'; // 输出7
    std::cout << str.find('w') << '\n'; // 输出7
    std::cout << str.find("abc") << '\n'; // 输出18446744073709551615(即string::npos)
}
//上面的代码会在控制台输出“7\n7\n18446744073709551615”。
if(in.find("qiandao")!=in.npos||in.find("easy")!=in.npos){
            continue;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值