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