在C++的字符串处理场景中,查找子串是最基础也最常用的操作之一,标准库string类提供的find函数是实现该需求的核心接口,它支持多种查找场景,适配不同的开发需求。

string find函数的基本语法
string类的find函数有多个重载版本,最基础的正向查找子串的语法如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world, welcome to cpp";
// 查找子串"world"在str中第一次出现的位置
size_t pos = str.find("world");
if (pos != string::npos) {
cout << "找到子串,位置为:" << pos << endl;
} else {
cout << "未找到子串" << endl;
}
return 0;
}
这里需要注意,find函数的返回值是size_t类型,也就是无符号整数,当查找失败时,会返回string::npos,这是一个静态常量,值通常是(size_t)-1,表示无效位置。
find函数的常见重载形式
1. 从指定位置开始查找
如果不想从字符串开头开始查找,可以传入第二个参数指定起始查找位置:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "cpp is great, cpp is powerful";
// 从第5个位置开始查找子串"cpp"
size_t pos = str.find("cpp", 5);
if (pos != string::npos) {
cout << "从位置5开始找到子串,位置为:" << pos << endl;
}
return 0;
}
2. 查找单个字符
find函数也支持查找单个字符,用法和查找子串类似:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "apple,banana,orange";
// 查找第一个逗号的位置
size_t pos = str.find(',');
if (pos != string::npos) {
cout << "第一个逗号位置:" << pos << endl;
// 查找逗号之后的第二个逗号
size_t next_pos = str.find(',', pos + 1);
if (next_pos != string::npos) {
cout << "第二个逗号位置:" << next_pos << endl;
}
}
return 0;
}
3. 反向查找子串:rfind函数
如果需要查找子串最后一次出现的位置,可以使用rfind函数,它从字符串末尾开始向前查找:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "test1 test2 test1 test3";
// 查找"test1"最后一次出现的位置
size_t pos = str.rfind("test1");
if (pos != string::npos) {
cout << "子串最后一次出现的位置:" << pos << endl;
}
return 0;
}
常见注意事项
- 查找失败的判断必须和
string::npos比较,不要直接和-1比较,因为不同编译器下string::npos的具体实现可能有差异,但和string::npos比较是通用写法。 - 如果查找的子串长度为0,find函数会直接返回起始查找位置,不会报错,实际开发中要注意避免传入空子串的场景。
- find函数是大小写敏感的,如果需要忽略大小写查找,需要自己先统一字符串和子串的大小写,再调用find函数。
查找结果的应用示例
实际开发中经常需要根据查找结果截取字符串,比如提取邮箱的用户名和域名部分:
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = "user@ipipp.com";
size_t at_pos = email.find('@');
if (at_pos != string::npos) {
string username = email.substr(0, at_pos);
string domain = email.substr(at_pos + 1);
cout << "用户名:" << username << endl;
cout << "域名:" << domain << endl;
}
return 0;
}
上面的代码中,先通过find函数找到@符号的位置,再用substr函数截取对应部分的字符串,完成邮箱信息的拆分。
C++string_findsubstring字符串查找修改时间:2026-07-03 21:24:13