C++ string::find 方法详解与使用示例
功能概述
string::find 用于在字符串中查找指定子串或字符的第一个匹配位置(不修改原字符串)。查找到第一个位置即结束,如需继续查找需配合循环。
函数原型
// 查找子串 str,从 pos 位置开始
size_t find(const string& str, size_t pos = 0) const;
// 查找单个字符 c,从 pos 位置开始
size_t find(char c, size_t pos = 0) const;
参数说明
str/c:要查找的子串或字符。pos:起始查找位置(可选,默认从 0 开始)。
返回值
- 找到时:返回匹配的第一个字符的索引(
size_t类型)。 - 未找到时:返回
string::npos(静态常量,表示不存在)。
注意:判断是否找到需用
== string::npos。由于string.size()返回size_t,建议统一使用size_t而非int以避免类型警告。
基础示例
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello, World!";
// 查找子串 "Wo"
size_t pos1 = s.find();
(pos1 != string::npos) {
cout << << pos1 << endl;
}
pos2 = s.(, );
(pos2 != string::npos) {
cout << << pos2 << endl;
}
pos3 = s.();
(pos3 == string::npos) {
cout << << endl;
}
;
}

