c++ std::find函数

本文介绍了 C++ 标准模板库 (STL) 中 find 函数的基本用法及其参数说明。find 函数用于在一范围内查找指定值,并返回该值首次出现位置的迭代器。
template <class InputIterator, class T>
InputIterator find (InputIterator first,InputIterator last,​ const T& val);

firstlast

分别指向一个序列中初始及末尾位置的输入迭代器。这个范围即 [first,last) ,包括 first 到 last 间的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。

val

需要被搜索的值。

返回

返回指向范围中与 val 等值的第一个元素的迭代器。

如果没有元素匹配,则返回 last 迭代器。

### C++ 中 `std::string::find` 方法的使用指南 `std::string::find` 是 C++ 标准库中用于在字符串中查找子字符串或字符的方法。它提供了多种重载形式,可以满足不同的查找需求[^4]。 #### 函数原型 以下是 `std::string::find` 的主要函数原型: ```cpp size_t find(const string& str, size_t pos = 0) const; size_t find(const char* s, size_t pos = 0) const; size_t find(char c, size_t pos = 0) const; ``` #### 参数说明 - `str`:要查找的子字符串。 - `s`:要查找的 C 风格字符串。 - `c`:要查找的单个字符。 - `pos`:开始查找的起始位置,默认为 0。 #### 返回值 如果找到目标字符串或字符,`std::string::find` 返回其第一次出现的位置(从 0 开始计数)。如果未找到,则返回 `std::string::npos`,这是一个特殊的常量,表示查找失败[^4]。 #### 示例代码 以下是一些常见的用法示例: ##### 查找子字符串 ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; std::string sub = "world"; size_t found = str.find(sub); if (found != std::string::npos) { std::cout << "Substring found at position: " << found << std::endl; } else { std::cout << "Substring not found" << std::endl; } return 0; } ``` ##### 查找单个字符 ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; char c = 'o'; size_t found = str.find(c); if (found != std::string::npos) { std::cout << "Character found at position: " << found << std::endl; } else { std::cout << "Character not found" << std::endl; } return 0; } ``` ##### 指定起始位置查找 ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; char c = 'o'; size_t pos = 5; size_t found = str.find(c, pos); if (found != std::string::npos) { std::cout << "Character found at position: " << found << std::endl; } else { std::cout << "Character not found after position " << pos << std::endl; } return 0; } ``` #### 注意事项 1. 如果需要查找所有匹配项,可以通过循环调用 `find` 并更新起始位置来实现[^4]。 2. 使用 `std::string::npos` 判断查找结果时,需确保正确处理未找到的情况。 3. `std::string::find` 是区分大小写的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值