basic_string::at

提供对字符在字符串中的指定索引。

const_reference at(
    size_type _Off
) const;
reference at(
    size_type _Off
);

参数

  • _Off
    元素的位置的索引中引用的。

返回值

为字符串的字符的引用将参数索引指定的位置。

备注

该字符串的第一个元素的索引零,并且正整数顺序标记的以下元素,因此,长度 n 字符串具有该数字标记中的 第n个元素 n – 1。

该成员 operator[] 比读取提供的成员函数 at 快且为字符串的组件编写。

该成员 operator[] 不检查作为参数传递的索引是否有效,但成员函数 at 执行,所以应使用,则正确性不确定。无效的索引,该索引零或大于或等于该字符串的大小,通过指向成员函数 at 引发 out_of_range选件类 异常。无效的索引传递给 operator[] 导致未定义的行为,但是,索引等于该字符串的长度是常数字符串的有效索引,而运算符返回Null字符,同时通过该索引。

返回的引用可能由字符串重新分配或修改无效的非const 字符串的。

示例

// basic_string_at.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "Hello world" ), str2 ( "Goodbye world" );
   const string  cstr1 ( "Hello there" ), cstr2 ( "Goodbye now" );
   cout << "The original string str1 is: " << str1 << endl;
   cout << "The original string str2 is: " << str2 << endl;

   // Element access to the non const strings
   basic_string <char>::reference refStr1 = str1 [6];
   basic_string <char>::reference refStr2 = str2.at ( 3 );

   cout << "The character with an index of 6 in string str1 is: "
        << refStr1 << "." << endl;
   cout << "The character with an index of 3 in string str2 is: "
        << refStr2 << "." << endl;

   // Element access to the const strings
   basic_string <char>::const_reference crefStr1 = cstr1 [ cstr1.length ( ) ];
   basic_string <char>::const_reference crefStr2 = cstr2.at ( 8 );

   if ( crefStr1 == '\0' )
      cout << "The null character is returned as a valid reference."
           << endl;
   else
      cout << "The null character is not returned." << endl;
   cout << "The character with index 8 in the const string cstr2 is: "
        << crefStr2 << "." << endl;
}

Output

The original string str1 is: Hello world
The original string str2 is: Goodbye world
The character with an index of 6 in string str1 is: w.
The character with an index of 3 in string str2 is: d.
The null character is returned as a valid reference.
The character with index 8 in the const string cstr2 is: n.

要求

标头: <string>

命名空间: std

请参见

参考

basic_string Class