[C.C++] 【C++】C++中的find方法介绍

725 0
Honkers 2025-10-14 21:55:20 来自手机 | 显示全部楼层 |阅读模式

目录

一.find方法基本用法

1.查找字符

2.查找子字符串

3.查找子字符串(从指定位置开始)

4.查找字符范围

5.查找不包含特定字符的范围

二.使用string::npos返回无效位置

三.总结


在C++中, std::string  类的  find  成员函数用于查找子字符串在字符串中的位置。 find  函数有多个重载版本,允许你以不同的方式执行查找操作。

一.find方法基本用法

  1. #include <iostream>
  2. #include <string>
  3. int main() {
  4.     std::string str = "Hello World!";
  5.     size_t pos = str.find("World");
  6.     if (pos != std::string::npos) {
  7.         std::cout << "Found 'World' at position: " << pos << std::endl;
  8.     } else {
  9.         std::cout << "The substring 'World' was not found." << std::endl;
  10.     }
  11.     return 0;
  12. }
复制代码

在这个示例中, find  被用来查找子字符串  "World"  在字符串  str  中的位置。如果找到了, pos  将包含子字符串的起始索引;如果没有找到, pos  将被设置为 std::string::npos 。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行