c++中substr函数用法

c++ 中 substr() 函数用于从字符串中提取子串。其用法为:起始位置: 指定子串的起始位置(从 0 开始)。长度(可选): 指定子串的长度,如果不指定则提取到字符串末尾。例如:string str = "hello, world!";substring1 = str.substr(7); // 提取 "world!"substring2 = str.substr(7, 5); // 提取 "world"

c++中substr函数用法

C++ 中 substr() 函数用法

substr() 函数是 C++ 标准库中 string 类的成员函数,用于从 string 对象中提取一个子串。

用法:

string substr(size_t pos, size_t len) const;

参数:

  • pos:子串的起始位置(从 0 开始)。
  • len(可选):要提取的子串的长度。如果不指定,则提取从起始位置到字符串末尾的所有字符。

返回值:

一个新的 string 对象,包含提取的子串。

示例:

std::string str = "Hello, world!";

// 提取从索引 7 开始的子串
std::string substring1 = str.substr(7);

// 提取从索引 7 开始,长度为 5 的子串
std::string substring2 = str.substr(7, 5);
登录后复制

在上述示例中,substring1 的值为 "world!",而 substring2 的值为 "world"。

注意事项:

  • pos 参数必须小于或等于字符串的长度。
  • len 参数不能大于字符串的长度减去 pos。
  • 如果 pos 或 len 超出范围,substr() 函数将抛出 std::out_of_range 异常。

以上就是c++++中substr函数用法的详细内容,更多请关注小编网其它相关文章!

转载请说明出处 内容投诉内容投诉
南趣百科 » c++中substr函数用法

南趣百科分享生活经验知识,是您实用的生活科普指南。

查看演示 官网购买