在C++中,substr()函数是用来提取字符串的子串的。它接受两个参数:起始位置和子串长度。
以下是substr()函数的用法:
string substr (size_t pos, size_t len) const;参数说明:
pos:子串的起始位置,从0开始计数。len:子串的长度。如果未指定此参数,则提取从起始位置到字符串末尾的所有字符。返回值:
返回一个新的字符串,表示原始字符串的子串。示例用法:
#include <iostream>#include <string>int main() { std::string str = "Hello, World!"; std::string sub1 = str.substr(7); // 从位置7开始提取子串 std::cout << sub1 << std::endl; // 输出:World! std::string sub2 = str.substr(0, 5); // 从位置0开始提取长度为5的子串 std::cout << sub2 << std::endl; // 输出:Hello return 0;}请注意,substr()函数返回的是一个新的字符串,而不是修改原始字符串。

