C++ std::string 类的 substr 函数

在 C++ 中,std::string 类的 substr 函数用于从字符串中提取一个子字符串。这个函数非常实用,常用于字符串处理任务。以下是 substr 函数的基本用法和细节:

函数原型

substr 函数的原型如下:

cpp 复制代码
string substr(size_t pos = 0, size_t len = npos) const;

参数

  • pos: 起始位置索引(从 0 开始),指明从哪个位置开始提取子字符串。
  • len : 长度,指明需要提取的字符数。如果 len 超出了字符串的剩余长度,函数只会提取从 pos 开始到字符串末尾的部分。
  • nposstd::string 类的一个静态成员,表示最大可能的字符串长度。

返回值

  • 返回一个 std::string 对象,包含从 pos 开始的、长度为 len 的子字符串。

示例

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, World!";
    
    // 提取从位置 7 开始的 5 个字符
    string substr1 = str.substr(7, 5); // "World"

    // 从位置 2 开始到字符串末尾
    string substr2 = str.substr(2); // "llo, World!"

    cout << substr1 << endl;
    cout << substr2 << endl;

    return 0;
}

注意事项

  • 如果 pos 超出了字符串的长度,substr 会抛出 std::out_of_range 异常。
  • 如果 pos 有效但 pos + len 超出了字符串的长度,将只提取从 pos 开始到字符串末尾的部分。

substr 函数是处理 C++ 字符串的一个非常有用的工具,它简化了许多涉及字符串分割和提取的操作。

相关推荐
weixin_4723394644 分钟前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击1 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue3 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
tan180°3 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
m0_555762903 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊4 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
彭祥.5 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
lzb_kkk5 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼5 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
简佐义的博客6 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang