1. 程式人生 > >c++怎麼提取字串的一部分

c++怎麼提取字串的一部分

C++的string類提供了大量的字串操作函式,提取字串的一部分,可採用substr函式實現:

  • 標頭檔案:

    #include <string> //注意沒有.h  string.h是C的標準字串函式數,c++中一般起名為ctring.  而string標頭檔案是C++的字串標頭檔案。

  • 函式原型:

    string substr(int pos = 0,int n ) const;

  • 函式說明:

     

    引數1pos是可預設引數,預設為0,即:從字串頭開始讀取。

    引數2n表示取多少個字元

    該函式功能為:返回從pos開始的n個字元組成的字串,原字串不被改變

參考程式碼:

1

2

3

4

5

6

7

8

9

10

#include <iostream>

#include <string>

using namespace std ;

void main()

{

    string s="ABAB";

    cout << s.substr(2) <<endl ; 

//輸出AB

    cout << s.substr(0,2) <<endl ; //同上

    cout << s.substr(1,2) <<endl ; //輸出BA

}