C++(find())
在 C++ 中,find()
函数是字符串类(std::string
)的成员函数,用于在字符串中查找特定的子字符串或字符。这函数有两个主要版本:一个是用于查找字符的版本,另一个用于查找子字符串的版本。
查找字符版本:
size_t find(const char& ch, size_t pos = 0) const;
- 参数:
ch
:要查找的字符。pos
:可选参数,指定开始查找的位置,默认为 0。
- 返回值:
- 如果找到字符,则返回找到的第一个字符的位置索引;如果未找到,返回
std::string::npos
。
- 如果找到字符,则返回找到的第一个字符的位置索引;如果未找到,返回
示例:
std::string str = "Hello, World!";
size_t position = str.find('W');
if (position != std::string::npos) {
std::cout << "Found at position: " << position << std::endl;
} else {
std::cout << "Not found." << std::endl;
}
查找子字符串版本:
size_t find(const std::string& str, size_t pos = 0) const;
- 参数:
str
:要查找的子字符串。pos
:可选参数,指定开始查找的位置,默认为 0。
- 返回值:
- 如果找到子字符串,则返回找到的第一个字符的位置索引;如果未找到,返回
std::string::npos
。
- 如果找到子字符串,则返回找到的第一个字符的位置索引;如果未找到,返回
示例:
std::string str = "Hello, World!";
size_t position = str.find("World");
if (position != std::string::npos) {
std::cout << "Found at position: " << position << std::endl;
} else {
std::cout << "Not found." << std::endl;
}
使用 find()
查找多个匹配:
可以使用循环结构和适当的处理,多次调用 find()
来查找多个匹配。
std::string str = "Hello, Hello, World!";
size_t pos = 0;
while ((pos = str.find("Hello", pos)) != std::string::npos) {
std::cout << "Found at position: " << pos << std::endl;
pos += 5; // Move past the found substring to avoid infinite loop
}
这样的循环可以找到字符串中所有匹配的子字符串的位置。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
2021-12-14 Python del、pop()、remove()、clear()
2021-12-14 Python 浮点型精度问题