C++ 中 substr 函数用于从原始字符串中提取子字符串。它有三个参数:起始位置、长度和返回值(一个新的包含子字符串的字符串)。用法包括提取完整子字符串、指定长度子字符串和到字符串末尾的子字符串。需要注意异常处理和特殊长度值。

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