【C++函数速查】substr字符串截取函数详解

文章目录

1)函数使用

  • s u b s t r substr substr 函数用于截取字符串, s u b s t r ( p o s ,   n ) substr(pos,\ n) substr(pos, n) 指从指定字符串的 p o s pos pos 索引起向后截取 n n n 个字符,本函数的使用方法比较简单且易于理解,具体使用方法见代码
#include<bits/stdc++.h>
#define x first
#define y second

using namespace std;

typedef long long ll;
typedef pair<int,int> PII;

// 解题思路: 

const int N=1e5+5;

int main() {
	string s="01234567"; // 索引从0开始
	
	string s1=s.substr(); // 1)不传参等价于复制字符串
	cout<<s1<<endl; // 01234567
	
	string s2=s.substr(0,2); // 2)传递2个参数,截取从字符串s下标0开始往后的2个字符
	cout<<s2<<endl; // 01
	
	string s3=s.substr(4); // 3)传递1个参数,截取s索引为4到字符串尾部
	cout<<s3<<endl; // 4567
	
	string s4=s.substr(8); // 4)若pos超过了string的大小,不抛出异常但没有输出
	cout<<s4<<endl; // 不输出
	
	string s5=s.substr(2,10); // 5)若pos+n超过了string的大小,则自动调整n的值,最多只截取到s的末尾
	cout<<s5<<endl; // 234567
	
	string s6=s.substr(-1); // 6)pos传入负值,抛出out_of_range异常(RE运行时错误)
	cout<<s6<<endl; // 报错,RE
	
	string s7=s.substr(3,-2); // 7)n传入负值,则默认截取到字符串末尾
	cout<<s7<<endl; // 34567
	return 0;
}
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值