C++ std::string::substr() 从指定下标起截取一段,返回新的 string,不修改原对象。省略长度时截取到末尾。
原型
string substr(size_t pos = 0, size_t count = npos) const;参数
pos:起始下标。count:最多截取的字符数;超出剩余长度时只取到末尾。
返回值
新字符串。若 pos 大于 size(),抛出 std::out_of_range。
示例
#include <iostream>
#include <string>
int main() {
std::string s = "online-compiler";
std::cout << s.substr(0, 6) << std::endl;
std::cout << s.substr(7) << std::endl;
return 0;
}输出:
online
compiler
注意事项
substr 会复制字符。频繁截取长串时注意分配开销。起始位置来自 find 时,须先确认不是 npos,再传入 substr。
下一页介绍replace:替换指定区间。