【c++string截取字符串】

文章目录


C++的string类提供了大量的字符串操作函数,提取字符串的一部分,可采用substr函数实现。

头文件:

#include <string> //注意没有.h

string.h是C的标准字符串函数数,c++中一般起名为ctring。而string头文件是C++的字符串头文件。

函数原型:

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

函数说明:

参数1:pos是必填参数。

参数2:n是可参数,表示取多少个字符,不填表示截取到末尾。

该函数功能为:返回从pos开始的n个字符组成的字符串,原字符串不被改变。

参考代码:

#include <iostream>
#include <string>
using namespace std ;
void main()
{
    
    
    string s="ABCD";
    cout << s.substr(2) <<endl ; //从字符串下标为2的地方开始截取,截取到末尾,输出CD
    cout << s.substr(0,2) <<endl ; //从字符串下标为0的地方开始截取,截取长度为2,输出AB
    cout << s.substr(1,2) <<endl ; //输出BC
}

猜你喜欢

转载自blog.csdn.net/weixin_42483745/article/details/127043034