std::string::find_first_of用于查找字符串中第一个出现在指定字符集中的字符位置,示例中查找元音字母返回索引1,与find_first_not_of区别在于前者匹配集合内字符,后者匹配集合外字符,适用于查找数字、标点等场景,不同于find子串的函数。

在C++中,std::string::find_first_of 是一个常用的字符串查找函数,用于在字符串中查找第一个出现在指定字符集合中的字符位置。它常被误认为是查找子串的函数,但实际上它的作用是“查找第一个匹配任意给定字符的位置”。
std::string::find_first_of 基本用法
该函数定义在 std::string 类中,有以下常见原型:
size_type find_first_of(const string& str, size_type pos = 0) const;size_type find_first_of(const char* s, size_type pos = 0) const;
size_type find_first_of(const char* s, size_type pos, size_type n) const;
size_type find_first_of(char c, size_type pos = 0) const;
说明:
- str / s / c:要搜索的字符或字符集
- pos:从哪个位置开始查找(默认从0开始)
- 返回值:找到则返回第一个匹配字符的索引;未找到返回 std::string::npos
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include iostream>
int main() {
std::string text = "Hello, World!";
size_t found = text.find_first_of("aeiou"); // 查找第一个元音字母
if (found != std::string::npos) {
std::cout }
// 输出:第一个元音字母位于:1 ('e')
return 0;
}
与 std::find_first_not_of 的区别
find_first_of 找的是“包含在集合中的第一个字符”,而 find_first_not_of 找的是“不在集合中的第一个字符”。
例如:
std::string s = "abc123def";size_t p1 = s.find_first_of("0123456789"); // 找到 '1',返回3
size_t p2 = s.find_first_not_of("abcdef"); // 找到 '1',也返回3
常见使用场景
这个函数适合用于:
- 查找字符串中第一个数字:
str.find_first_of("0123456789") - 查找第一个标点符号或分隔符:
str.find_first_of(",.!;:") - 验证输入是否包含非法字符
- 解析文本时跳过特定字符集
注意:它不是用来查找完整子串的。如果要找子串,应使用 std::string::find()。
与 std::find 算法的区别
有人会混淆 std::string::find_first_of 和标准算法库中的 std::find 或 std::find_if。
- std::find:在迭代器范围内查找某个特定值
- std::find_if:根据条件查找第一个满足谓词的元素
- std::string::find_first_of:在字符串中查找第一个出现在给定字符集中的字符
对比示例:
#include#include
std::string data = "test123";
// 使用 find_first_of 查找第一个数字
size_t pos1 = data.find_first_of("0123456789");
// 使用 std::find_if 实现相同功能
auto it = std::find_if(data.begin(), data.end(), ::isdigit);
size_t pos2 = (it != data.end()) ? (it - data.begin()) : std::string::npos;
两者效果类似,但 find_first_of 更简洁直观,专为字符串设计。
基本上就这些。掌握 find_first_of 能让你更高效地处理字符串中的字符分类查找问题,避免手动遍历循环。










