C++中查找子串主要使用std::string的find()函数,1. find()返回子串首次出现位置,未找到则返回npos;2. 可指定起始位置查找多个匹配项;3. rfind()从右查找最后一次出现位置;4. 注意size_t类型、检查npos及大小写敏感问题。

在C++中查找字符串中的子串是日常编程中常见的操作。C++标准库提供了多种方法来实现这一功能,主要依赖于std::string类自带的成员函数。本文将介绍几种常用的字符串查找方式,帮助你高效地完成子串搜索任务。
find() 是最常用的字符串查找函数,用于在原字符串中搜索指定的子串或字符。如果找到,返回子串首次出现的起始位置(索引);如果未找到,返回 std::string::npos。
基本语法:
size_t pos = str.find("substring");
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, welcome to C++ programming!";
std::string pattern = "welcome";
size_t pos = text.find(pattern);
if (pos != std::string::npos) {
std::cout << "子串在位置 " << pos << " 找到。\n";
} else {
std::cout << "未找到子串。\n";
}
return 0;
}
find() 还支持从某个指定位置开始搜索,适用于需要查找多个匹配项的情况。
语法:
str.find(substring, start_pos);
示例:查找所有匹配的子串位置
std::string text = "She sells seashells by the seashore.";
std::string pattern = "se";
size_t pos = 0;
while ((pos = text.find(pattern, pos)) != std::string::npos) {
std::cout << "找到子串在位置: " << pos << "\n";
pos += pattern.length(); // 避免重复查找同一位置
}
C++还提供了其他几个查找函数,满足不同需求:
例如使用 rfind() 查找最后一次出现的子串:
size_t pos = text.rfind("sea");
if (pos != std::string::npos) {
std::cout << "最后一次出现位置: " << pos << "\n";
}
使用字符串查找函数时需注意以下几点:
基本上就这些。熟练掌握 find 及其相关函数,能让你在处理文本时更加得心应手。不复杂但容易忽略细节,比如 npos 的判断和查找起点控制。多练习几种场景,就能灵活运用了。
以上就是c++++如何查找字符串中的子串_c++字符串查找函数使用指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号