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;
}

 

posted @ 2020-08-17 15:16  r1-12king  阅读(5761)  评论(0编辑  收藏  举报