c++ substr()函数的用法


函数原型

string substr (size_t pos = 0, size_t len = npos) const;

功能描述:

  • 从字符串中获取想要的子串

参数:

  pos:

    • 要作为子字符串复制的第一个字符的位置。
    • 如果等于字符串长度,则该函数返回一个空字符串。
    • 如果该长度大于字符串长度,则抛出out_of_range。
    • 注意:第一个字符由0值表示(不是1)。

  len:

    • 子字符串中要包含的字符数(如果字符串较短,则使用尽可能多的字符)。
    • string :: npos的值表示直到字符串末尾的所有字符。

返回值:

  • 带有此对象子字符串的字符串对象。

 

样例:

// string::substr
#include <iostream>
#include <string>

int main ()
{
    std::string str="We think in generalities, but we live in details.";

    std::string str2 = str.substr (3,5);     // "think"

    std::size_t pos = str.find("live");      // position of "live" in str

     std::string str3 = str.substr (pos);     // get from "live" to the end

    std::cout << str2 << ' ' << str3 << '\n';

    return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM