当前位置:   article > 正文

c++---substr()函数_substr函数c++

substr函数c++

在C++中,substr 函数用于从字符串中提取子字符串。它的具体功能是返回一个新的字符串,该字符串包含原始字符串中从指定位置开始的指定长度的字符。
substr 函数有两种常用的用法:
1.substr(pos, len): 从指定位置pos开始,提取长度为len的子字符串。
2.substr(pos): 从指定位置pos开始,提取到原始字符串的末尾的子字符串。
用法:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 从位置为7开始,提取长度为5的子字符串
    std::string sub1 = str.substr(7, 3);
    std::cout << "sub1: " << sub1 << std::endl;  // 输出: "Wor"

    // 从位置为7开始,提取到末尾的子字符串
    std::string sub2 = str.substr(7);
    std::cout << "sub2: " << sub2 << std::endl;  // 输出: "World!"

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在这里插入图片描述

substr 函数被用来从字符串 “Hello, World!” 中提取子字符串。第一个 substr 调用提取了从位置 7 开始长度为 3 的子字符串,而第二个 substr 调用提取了从位置 7 开始到末尾的子字符串。

满堂花醉三千客,一剑霜寒十四州。
2024年3月20日21:35:48

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/490469
推荐阅读
相关标签
  

闽ICP备14008679号