c++ string.find()参数说明

本文详细介绍了C++中的string.find()函数,包括参数含义和使用方法。通过实例展示了如何在字符串中查找指定子串,以及查找过程中的一些注意事项,如查找范围的设定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ string.find()参数说明

int find(string s, int m, int n)

假设母字符串为str.
该函数实现的是在 str 中的第m个位置往后开始查找目标字符串s的前n个字符,返回找到的第一个出现字符串首字母的位置,若没找到,则返回-1.
说明:

  • 第一个参数是要查找的字符串s.
  • 第二个参数是母字符串中查找的起始位置。
  • 第三个参数是目标字符串的前n个字符。或者说第三个参数为指出字符的个数。

示例:

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str = "ABCDAEFG88991456188A";
	int pos1 = str.find("A", 0, 1);
	int pos2 = str.find("A", 1, 1); // 从str的1位置开始往后找“A”
	int pos3 = str.find("A", 0, 2); // 这里由于2超出了“A”的长度,所以返回-1
	int pos4 = str.find("88A", 0, 3); // 从str的3位置开始往后找“88A”
	int pos5 = str.find("88A", 0, 2); // 从str的0位置开始往后找“88”
	int pos6 = str.find("88A", 9, 2); // 从str的9位置开始往后找“88”
	int pos7 = str.find("88A", 0, 1); // 从str的0位置开始往后找“8”
	

	cout << pos1 << endl;
	cout << pos2 << endl;
	cout << pos3 << endl;
	cout << pos4 << endl;
	cout << pos5 << endl;
	cout << pos6 << endl;
	cout << pos7 << endl;


	system("pause");
	return 0;
}

输出为:

0
4
-1
17
8
17
8
### C++ `string::find` 函数的用法 在C++标准库中,`std::string` 提供了一个成员函数 `find` 来定位子字符串的位置。如果找到匹配项,则返回该位置;如果没有找到,则返回 `std::string::npos`。 #### 基础语法 ```cpp size_t find(const string& str, size_t pos = 0) const noexcept; ``` - 参数 `str`: 要查找的子串。 - 参数 `pos`: 开始查找的位置,默认为0表示从头开始[^1]。 #### 实际应用案例 下面是一个完整的代码示例展示如何使用 `string::find` 方法: ```cpp #include <iostream> #include <string> int main() { std::string s = "hello world"; // 查找单个字符 'o' size_t index_char = s.find('o'); if (index_char != std::string::npos) std::cout << "'o' first occurs at position: " << index_char << '\n'; // 查找整个单词 "world" size_t index_word = s.find("world"); if (index_word != std::string::npos) std::cout << "\"world\" starts from position: " << index_word << '\n'; // 尝试在一个不存在的情况下寻找 size_t missing_index = s.find("universe"); if (missing_index == std::string::npos) std::cout << "The word \"universe\" is not present.\n"; return 0; } ``` 这段程序展示了三种情况下的查找操作:成功查找到了单个字符、成功查到了一个词组以及未能发现目标的情况。 #### 处理找不到的情形 当调用 `find` 并且未找到指定模式时,它会返回特殊值 `std::string::npos`。因此,在实际编程实践中应当始终检查此返回值以确认是否真的发现了所要找的内容。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值