赞
踩
在C++中,substr 函数用于从字符串中提取子字符串。它的具体功能是返回一个新的字符串,该字符串包含原始字符串中从指定位置开始的指定长度的字符。
substr 函数有两种常用的用法:
1.substr(pos, len): 从指定位置pos开始,提取长度为len的子字符串。
2.substr(pos): 从指定位置pos开始,提取到原始字符串的末尾的子字符串。
用法:
#include <iostream> #include <string> int main() { std::string str = "Hello, World!"; // 从位置为7开始,提取长度为5的子字符串 std::string sub1 = str.substr(7, 3); std::cout << "sub1: " << sub1 << std::endl; // 输出: "Wor" // 从位置为7开始,提取到末尾的子字符串 std::string sub2 = str.substr(7); std::cout << "sub2: " << sub2 << std::endl; // 输出: "World!" return 0; }
substr 函数被用来从字符串 “Hello, World!” 中提取子字符串。第一个 substr 调用提取了从位置 7 开始长度为 3 的子字符串,而第二个 substr 调用提取了从位置 7 开始到末尾的子字符串。
满堂花醉三千客,一剑霜寒十四州。
2024年3月20日21:35:48
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。