C++提取子字符串

substr() 函数可以提取 string 字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。

举个例子:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second third";
    string s2;
    s2 = s1.substr(6, 6);
    cout<< s1 <<endl;
    cout<< s2 <<endl;
    return 0;
}
程序运行结果:

first second third
second

该函数同样会出现参数越界的情况,如果第一个参数越界,则函数会抛出异常。在第一个参数没有越界的情况下,第二个参数仍然会导致越界,该函数的处理方式与前面提到的 erase() 函数、replace() 函数相同,子字符串最多从第一个参数所指明的下标开始一直延续到字符串结尾。