一句话理解
substr(pos, len) 取出从 pos 开始、长度为 len 的子串。
为什么要学
切出一段文字、枚举子串。
讲解
pos 是 0-based。s.substr(1, 2) 从下标 1 取两个字符。
只写 s.substr(pos) 表示一直取到末尾。
pos 超出范围会抛异常(可能 RE)。len 太长则取到末尾为止。
例子
string s = "abcdef";
cout << s.substr(2, 3);
输出:
cde
下标 2 是 c,取 3 个:cde。
常见错误
- 把 pos 当成 1-based。
- 循环里对每个区间 substr,可能变慢,有时直接下标比较更好。