substr函数是C++中string类的成员函数,用于获取一个字符串的子串。

函数原型如下:

string substr (size_t pos = 0, size_t len = npos) const;

其中,pos表示子串起始位置,len表示子串的长度,如果len超过了原字符串长度,则返回从pos开始到字符串末尾的所有字符。

函数返回值是一个新的string对象,表示从原字符串中提取的子串。

示例:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "Hello,world!";
    string substr1 = str.substr(0, 5); // 提取从0位置开始的5个字符,即"Hello"
    string substr2 = str.substr(7); // 提取从7位置开始到字符串末尾的所有字符,即"world!"

    cout << "substr1: " << substr1 << endl; // 输出"substr1: Hello"
    cout << "substr2: " << substr2 << endl; // 输出"substr2: world!"
    
    return 0;
}

注意:

  • 如果pos的值超过了原字符串的长度,则会抛出out_of_range异常。
  • substr函数不改变原字符串的内容,而是返回一个新的字符串对象。
  • substr函数返回的字符串对象的长度为len,如果len为0,则返回空字符串。
C++中的substr函数详细解说

原文地址: https://www.cveoy.top/t/topic/i64 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录