string.substr()函数

文章目录

1.介绍

 A. 函数原型:
在这里插入图片描述
  返回 string 字符串上[ pos, pos + count ) 位置上面的子字符串

2.分析

 A. 头文件:iostream

 B. 使用细节分析:

    string s = "abcdef";

  1. 若两个参数全部省略,则默认返回整个字符串

    cout << s.substr() << endl; // abcdef

  2. 若省去第二个参数,则默认第二个参数的值为字符串size() - pos (默认到字符串结尾)

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

  3. 越界处理第一个参数越界(过小 / 过大)都会报错,第二个参数越界会直接默认到字符串结尾

    cout << s.substr(-1) << ' ' << s.substr(7) << endl; // 抛出错误异常
    cout << s.substr(2, 100) <<endl; // cdef

3.使用

#include<iostream>
#include<cstring>
using namespace std;

int main(){
    
    
    string s = "abcdef";
    cout << s.substr() << endl; // abcdef
    cout << s.substr(2) << endl; // cdef
    // cout << s.substr(-1) << ' ' << s.substr(7) << endl; // 抛出错误异常
    cout << s.substr(2, 100) <<endl; // cdef

}

猜你喜欢

转载自blog.csdn.net/weixin_51566349/article/details/130205620