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

}

猜你喜欢

转载自blog.csdn.net/myyllove/article/details/83302416
今日推荐