C++ 标准库 - <string>

C++ std::string::at() 按下列标访问单个字符;下标不合法时抛出 std::out_of_range。operator[] 不检查越界,教学示例中常用 [],库边界处更稳妥的是 at。

原型

char& at(size_t pos);
const char& at(size_t pos) const;

参数

  • pos:下标,合法范围为 0 到 size() - 1(空串不可访问)。

返回值

对应位置的字符引用。越界抛出异常。

示例

#include <iostream>
#include <string>

int main() {
    std::string s = "abc";
    std::cout << s.at(1) << std::endl;
    return 0;
}

输出:

b

注意事项

已知下标来自循环且已用 size() 约束时,[] 开销更小。输入或计算结果可能越界时,应使用 at 或先判断范围。

下一页介绍c_str:得到 C 风格字符串指针。