다음을 통해 공유


basic_string::at

문자열에서 지정 된 인덱스에 있는 문자에 대 한 참조를 제공합니다.

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

매개 변수

  • _Off
    인덱스 위치를 참조 하는 요소입니다.

반환 값

매개 변수 인덱스가 지정 된 위치에 문자열의 문자에 대 한 참조.

설명

문자열의 첫 번째 요소 인덱스 0 있고 양수에서 연속적으로 인덱싱된 다음 요소 있도록 문자열의 길이 nnth 요소 인덱스 번호에서 n- 1.

멤버 operator 멤버 함수 보다 빠릅니다 읽기 및 쓰기 액세스 문자열의 요소를 제공 합니다.

멤버 operator[] 멤버 함수는 매개 변수로 전달 된 인덱스 여부 유효 하지만 확인 하지 않습니다 하지 하므로 사용 해야 유효성 특정 되지 않은 경우.0 인덱스 보다는 잘못 된 인덱스 또는 보다 크거나 멤버 함수에 전달 하 여 문자열의 크기를 throw 된 out_of_range 클래스 예외.전달 된 잘못 된 인덱스는 operator[] 결과에 정의 되지 않은 동작을 하지만 인덱스에 문자열의 길이 같은 const 문자열에는 유효한 인덱스 이며 연산자를 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