C++中substr函数的用法

basic_string substr(size_type _Off = 0, size_type _Count = npos) const;

在使用时,可以设置npos(拷贝长度),也可以不设置。

#include<string>
#include<iostream>
using namespace std;
int main()
{
 	string s = "12345abcdefff";

	string res1 = s.substr(1, 5);
	cout << res1 << endl;      //res1 = "12345"

	string res2 = s.substr(5, 5);    //第一个参数为pos的位置,也就是下标
	cout << res2 << endl;      //res2 = "abcde"

	string res3 = s.substr(5);     //不写最后一个参数,默认到字符串结尾
	cout << res3 << endl;      //res3 = "abcdefff"

	string res4 = s.substr(5, 10);    //第二个参数越界,但是可以正常取到字符串结尾停止
	cout << res4 << endl;      //res4 = "abcdefff"

	//注:如果第一个参数大于字符串长度是会报错的
}

返回值一个string,包含s中从pos开始的n个字符的拷贝。pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s。

注:
若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常
若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值