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++ 字符串的一个非常有用的工具,它简化了许多涉及字符串分割和提取的操作。

相关推荐
临床数据科学和人工智能兴趣组11 分钟前
R语言因其强大的统计功能、灵活的编程环境、活跃的社区支持和强大的R扩展包,迅速成为统计学和数据科学领域的首选工具之一
开发语言·数据分析·r语言·r语言-4.2.1
__log1 小时前
弱网环境下的“生命线“:从AI流式响应到大文件上传的稳定性
开发语言·人工智能·php
盐焗鹌鹑蛋1 小时前
【C++】C++11:列表初始化、声明、STL升级
c++
巧克力男孩dd1 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
TlSfoward1 小时前
TLSFOWARD TLS指纹
开发语言·数据库·爬虫·搜索引擎·https·php
闲猫2 小时前
LangChain / Core components / Models
开发语言·python·langchain
ComputerInBook3 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
AA陈超3 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
-银雾鸢尾-3 小时前
C#中的索引器
开发语言·c#
bu_shuo4 小时前
c与cpp中的argc和argv
c语言·c++·算法