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

相关推荐
一只专注api接口开发的技术猿几秒前
微服务架构下集成淘宝商品 API 的实践与思考
java·大数据·开发语言·数据库·微服务·架构
被星1砸昏头8 分钟前
C++中的享元模式
开发语言·c++·算法
2501_9444241211 分钟前
Flutter for OpenHarmony游戏集合App实战之记忆翻牌配对消除
android·java·开发语言·javascript·windows·flutter·游戏
m0_7482404416 分钟前
Laravel5.6核心更新全解析
开发语言·php
曹牧18 分钟前
C#:Obsolete
开发语言·c#
我是苏苏22 分钟前
Web开发:使用C#的System.Drawing.Common将png图片转化为icon图片
开发语言·c#
D_evil__32 分钟前
【Effective Modern C++】第三章 转向现代C++:7. 在创建对象时注意区分()和{}
c++
冬奇Lab34 分钟前
【Kotlin系列11】协程原理与实战(下):Flow与Channel驯服异步数据流
android·开发语言·kotlin
好大哥呀37 分钟前
如何在手机上运行Python程序
开发语言·python·智能手机
阿蒙Amon38 分钟前
C#每日面试题-is和as的区别
java·开发语言·c#