首页 > 后端开发 > C++ > 正文

C++如何使用std::string::find_first_of_C++字符串查找方法与std::find_first_of使用

穿越時空
发布: 2025-12-05 14:21:30
原创
987人浏览过
std::string::find_first_of用于查找字符串中第一个出现在指定字符集中的字符位置,示例中查找元音字母返回索引1,与find_first_not_of区别在于前者匹配集合内字符,后者匹配集合外字符,适用于查找数字、标点等场景,不同于find子串的函数。

c++如何使用std::string::find_first_of_c++字符串查找方法与std::find_first_of使用

在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 找的是“不在集合中的第一个字符”。

例如:

Riffo
Riffo

Riffo是一个免费的文件智能命名和管理工具

Riffo 216
查看详情 Riffo
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::findstd::find_if

  • std::find:在迭代器范围内查找某个特定值
  • std::find_if:根据条件查找第一个满足谓词的元素
  • std::string::find_first_of:在字符串中查找第一个出现在给定字符集中的字符

对比示例:

#include gorithm>
#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 能让你更高效地处理字符串中的字符分类查找问题,避免手动遍历循环。

以上就是C++如何使用std::string::find_first_of_C++字符串查找方法与std::find_first_of使用的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号