当前位置: 首页 > news >正文

C++中substr用法记录

在C++中,substr 是 std::string 类的一个成员函数,用于从一个字符串中提取子字符串。substr 函数的基本语法如下:

string substr(size_type pos = 0, size_type count = npos) const;

参数解释:

  1. pos

    • 类型:size_type(通常是 std::size_t
    • 含义:子字符串的起始位置。pos 是从 0 开始的索引。如果 pos 超过了字符串的长度,函数会抛出一个 std::out_of_range 异常。
  2. count

    • 类型:size_type
    • 含义:子字符串的长度。如果 count 超过了从 pos 开始的剩余字符数,子字符串将包含从 pos 开始的所有字符,直到字符串的末尾。

返回值:

  • 类型:std::string
  • 含义:返回一个包含了从 pos 开始的 count 个字符的子字符串。

使用示例:

  1. 提取从指定位置开始的子字符串

    #include <iostream>
    #include <string>int main() {std::string str = "Hello, World!";std::string sub = str.substr(7);  // 从索引 7 开始到末尾std::cout << sub << std::endl;    // 输出: World!return 0;
    }
    
  2. 提取指定长度的子字符串

    #include <iostream>
    #include <string>int main() {std::string str = "Hello, World!";std::string sub = str.substr(7, 5);  // 从索引 7 开始,提取 5 个字符std::cout << sub << std::endl;       // 输出: Worldreturn 0;
    }
    
  3. 提取从字符串末尾开始的子字符串

    #include <iostream>
    #include <string>int main() {std::string str = "Hello, World!";std::string sub = str.substr(str.size() - 6);  // 从倒数第 6 个字符开始到末尾std::cout << sub << std::endl;                // 输出: World!return 0;
    }
    
  4. 处理异常(如果起始位置超出字符串长度)

    #include <iostream>
    #include <string>int main() {std::string str = "Hello, World!";try {std::string sub = str.substr(20);  // 起始位置超出字符串长度} catch (const std::out_of_range& e) {std::cerr << "Out of range error: " << e.what() << std::endl;}return 0;
    }

http://www.mrgr.cn/news/41447.html

相关文章:

  • 云原生(四十一)| 阿里云ECS服务器介绍
  • 什么是 Supply chain attack(供应链攻击)
  • 差分基准站
  • MySQL高阶2051-商店中每个成员的级别
  • Blazor开发框架Known-V2.0.13
  • JavaWeb
  • 基于深度学习的乳腺癌分类识别与诊断系统
  • 【YOLO目标检测行人与车数据集】共5607张、已标注txt格式、有训练好的yolov5的模型
  • 【C++】set容器和map容器的基本使用
  • 探索 3 个有趣的 GitHub 学习资源库
  • 探索未来:掌握python-can库,开启AI通信新纪元
  • 龙芯1B开发板自检程序
  • 告别PPT熬夜!Kimi+AIPPT一键生成PPT,效率upup!
  • 90. 子集 II
  • [云] 将文件从本地机器传输到 EC2 实例
  • 重生之我们在ES顶端相遇第 18 章 - Script 使用(进阶)
  • 设计模式(2)工厂模式
  • TypeScript 封装 Axios 1.7.7
  • leetcode_198_打家劫舍
  • 【Docker】docker的存储