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

C++ 中 substr() 函数用法
substr() 函数是 C++ 标准库中 string 类的成员函数,用于从 string 对象中提取一个子串。
用法:
string substr(size_t pos, size_t len) const;
立即学习“C++免费学习笔记(深入)”;
参数:
pos:子串的起始位置(从 0 开始)。len(可选):要提取的子串的长度。如果不指定,则提取从起始位置到字符串末尾的所有字符。返回值:
一个新的 string 对象,包含提取的子串。
示例:
<code class="cpp">std::string str = "Hello, world!"; // 提取从索引 7 开始的子串 std::string substring1 = str.substr(7); // 提取从索引 7 开始,长度为 5 的子串 std::string substring2 = str.substr(7, 5);</code>
在上述示例中,substring1 的值为 "world!",而 substring2 的值为 "world"。
注意事项:
pos 参数必须小于或等于字符串的长度。len 参数不能大于字符串的长度减去 pos。pos 或 len 超出范围,substr() 函数将抛出 std::out_of_range 异常。以上就是c++++中substr函数用法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号