C++의 std::string 클래스

C++에는 정의에 다음을 나타내는 방법이 있습니다. 클래스의 객체로서의 문자 시퀀스 . 이 클래스를 std::string이라고 합니다. 문자열 클래스는 다음과 같은 기능을 사용하여 문자를 바이트 시퀀스로 저장합니다. 단일 바이트 문자에 대한 액세스 .

문자열 대 문자 배열

 문자열은 객체를 정의하는 클래스 문자 스트림으로 표현됩니다. 문자 배열은 단순히 문자 배열 null 문자로 끝날 수 있습니다.
문자열 메모리의 경우 동적으로 할당됨 . 요청 시 런타임에 더 많은 메모리를 할당할 수 있습니다. 메모리가 사전 할당되지 않기 때문에 기억은 낭비되지 않는다 . 문자 배열의 크기는 다음과 같아야 합니다. 정적으로 할당됨 필요한 경우 런타임에 더 많은 메모리를 할당할 수 없습니다. 미사용 할당 기억력도 낭비된다
문자열은 객체로 표현되기 때문에 배열 붕괴 없음 발생합니다. 있다 위협 배열 붕괴 문자 배열의 경우. 
문자열이 더 느립니다. 문자 배열보다 구현과 비교할 때. 구현 문자 배열이 더 빠릅니다. std:: 문자열보다 
문자열 클래스는 다음을 정의합니다. 여러 가지 기능 문자열에 대한 다양한 작업을 허용합니다. 문자 배열 제안하지 않는다 많은 내장된 기능 문자열을 조작합니다.

문자열에 대한 작업

1) 입력 기능

기능 정의
getline() 이 기능은 사용자가 개체 메모리에 입력한 문자 스트림을 저장하는 데 사용됩니다.
push_back() 문자열의 마지막에 문자를 입력할 때 사용하는 함수입니다.
팝백() C++11(문자열용)에서 도입된 이 함수는 문자열에서 마지막 문자를 삭제하는 데 사용됩니다. 

예:

CPP
   // C++ Program to demonstrate the working of   // getline() push_back() and pop_back()   #include          #include         // for string class   using     namespace     std  ;   // Driver Code   int     main  ()   {      // Declaring string      string     str  ;      // Taking string input using getline()      getline  (  cin       str  );      // Displaying string      cout      < <     'The initial string is : '  ;      cout      < <     str      < <     endl  ;      // Inserting a character      str  .  push_back  (  's'  );      // Displaying string      cout      < <     'The string after push_back operation is : '  ;      cout      < <     str      < <     endl  ;      // Deleting a character      str  .  pop_back  ();      // Displaying string      cout      < <     'The string after pop_back operation is : '  ;      cout      < <     str      < <     endl  ;      return     0  ;   }   

산출
The initial string is : The string after push_back operation is : s The string after pop_back operation is :  

시간 복잡도: O(1)

공간 복잡도: O(n) 여기서 n은 문자열의 크기입니다.

2) 용량 기능

기능 정의
용량() 이 함수는 문자열 크기보다 크거나 같을 수 있는 문자열에 할당된 용량을 반환합니다. Additional space is allocated so that when the new characters are added to the string the operations can be done efficiently.
크기 조정() 이 함수는 문자열의 크기를 변경하며 크기를 늘리거나 줄일 수 있습니다.
길이() 이 함수는 문자열의 길이를 구합니다.
Shrink_to_fit() 이 기능은 문자열의 용량을 줄여서 문자열의 최소 용량과 동일하게 만듭니다. 이 작업은 더 이상 문자를 추가할 필요가 없다고 확신하는 경우 추가 메모리를 절약하는 데 유용합니다.

예:

CPP
   // C++ Program to demonstrate the working of   // capacity() resize() and shrink_to_fit()   #include          #include         // for string class   using     namespace     std  ;   // Driver Code   int     main  ()   {      // Initializing string      string     str     =     'geeksforgeeks is for geeks'  ;      // Displaying string      cout      < <     'The initial string is : '  ;      cout      < <     str      < <     endl  ;      // Resizing string using resize()      str  .  resize  (  13  );      // Displaying string      cout      < <     'The string after resize operation is : '  ;      cout      < <     str      < <     endl  ;      // Displaying capacity of string      cout      < <     'The capacity of string is : '  ;      cout      < <     str  .  capacity  ()      < <     endl  ;      // Displaying length of the string      cout      < <     'The length of the string is :'      < <     str  .  length  ()       < <     endl  ;      // Decreasing the capacity of string      // using shrink_to_fit()      str  .  shrink_to_fit  ();      // Displaying string      cout      < <     'The new capacity after shrinking is : '  ;      cout      < <     str  .  capacity  ()      < <     endl  ;      return     0  ;   }   

산출
The initial string is : geeksforgeeks is for geeks The string after resize operation is : geeksforgeeks The capacity of string is : 26 The length of the string is :13 The new capacity after shrinking is : 13 

시간 복잡도: O(1)

공간 복잡도: O(n) 여기서 n은 문자열의 크기입니다.

3) 반복자 함수

기능 정의
시작하다() 이 함수는 문자열의 시작 부분에 대한 반복자를 반환합니다.
끝() 이 함수는 문자열 끝 옆에 반복자를 반환합니다.
rbegin() 이 함수는 문자열의 끝을 가리키는 역방향 반복자를 반환합니다.
세우다() 이 함수는 문자열의 시작 부분의 이전 부분을 가리키는 역방향 반복자를 반환합니다.
cbegin() 이 함수는 가리키는 내용을 수정하는 데 사용할 수 없는 문자열의 시작 부분을 가리키는 상수 반복자를 반환합니다.
몇() 이 함수는 가리키는 내용을 수정하는 데 사용할 수 없는 문자열의 다음 끝을 가리키는 상수 반복자를 반환합니다.
크르비긴() 이 함수는 가리키는 내용을 수정하는 데 사용할 수 없는 문자열의 끝을 가리키는 상수 역방향 반복자를 반환합니다.
트렌드() 이 함수는 가리키는 내용을 수정하는 데 사용할 수 없는 문자열의 시작 부분의 이전 부분을 가리키는 상수 역방향 반복자를 반환합니다.

연산:

  1. 문자열 선언
  2. 모든 유형의 반복자를 사용하여 문자열을 반복해 보십시오.
  3. 문자열 요소를 수정해 보세요.
  4. 모든 반복을 표시합니다.

예:

CPP
   // C++ Program to demonstrate the working of   // begin() end() rbegin() rend() cbegin() cend() crbegin() crend()   #include          #include         // for string class   using     namespace     std  ;   // Driver Code   int     main  ()   {      // Initializing string`      string     str     =     'geeksforgeeks'  ;      // Declaring iterator      std  ::  string  ::  iterator     it  ;      // Declaring reverse iterator      std  ::  string  ::  reverse_iterator     it1  ;      cout   < <  'Str:'   < <  str   < <  '  n  '  ;      // Displaying string      cout      < <     'The string using forward iterators is : '  ;      for     (  it     =     str  .  begin  ();     it     !=     str  .  end  ();     it  ++  ){      if  (  it     ==     str  .  begin  ())     *  it  =  'G'  ;      cout      < <     *  it  ;      }      cout      < <     endl  ;      str     =     'geeksforgeeks'  ;      // Displaying reverse string      cout      < <     'The reverse string using reverse iterators is '      ': '  ;      for     (  it1     =     str  .  rbegin  ();     it1     !=     str  .  rend  ();     it1  ++  ){      if  (  it1     ==     str  .  rbegin  ())     *  it1  =  'S'  ;      cout      < <     *  it1  ;      }      cout      < <     endl  ;          str     =     'geeksforgeeks'  ;      //Displaying String      cout   < <  'The string using constant forward iterator is :'  ;      for  (  auto     it2     =     str  .  cbegin  ();     it2  !=  str  .  cend  ();     it2  ++  ){      //if(it2 == str.cbegin()) *it2='G';      //here modification is NOT Possible      //error: assignment of read-only location       //As it is a pointer to the const content but we can inc/dec-rement the iterator      cout   < <*  it2  ;      }      cout   < <  '  n  '  ;          str     =     'geeksforgeeks'  ;      //Displaying String in reverse      cout   < <  'The reverse string using constant reverse iterator is :'  ;      for  (  auto     it3     =     str  .  crbegin  ();     it3  !=  str  .  crend  ();     it3  ++  ){      //if(it2 == str.cbegin()) *it2='S';      //here modification is NOT Possible      //error: assignment of read-only location       //As it is a pointer to the const content but we can inc/dec-rement the iterator      cout   < <*  it3  ;      }      cout   < <  '  n  '  ;      return     0  ;   }   //Code modified by Balakrishnan R (rbkraj000)   

산출
Str:geeksforgeeks The string using forward iterators is : Geeksforgeeks The reverse string using reverse iterators is : Skeegrofskeeg The string using constant forward iterator is :geeksforgeeks The reverse string using constant reverse iterator is :skeegrofskeeg 

시간 복잡도: O(1)

공간 복잡도: O(n) 여기서 n은 문자열의 크기입니다.

4) 기능 조작:

기능 정의
copy('문자 배열' len pos)  이 함수는 인수에 언급된 대상 문자 배열의 하위 문자열을 복사합니다. 복사할 대상 문자 배열 길이와 복사를 시작하려면 문자열의 시작 위치에 3개의 인수가 필요합니다.
교환() 이 함수는 한 문자열을 다른 문자열로 교환합니다.

예:

CPP
   // C++ Program to demonstrate the working of   // copy() and swap()   #include          #include         // for string class   using     namespace     std  ;   // Driver Code   int     main  ()   {      // Initializing 1st string      string     str1     =     'geeksforgeeks is for geeks'  ;      // Declaring 2nd string      string     str2     =     'geeksforgeeks rocks'  ;      // Declaring character array      char     ch  [  80  ];      // using copy() to copy elements into char array      // copies 'geeksforgeeks'      str1  .  copy  (  ch       13       0  );      // Displaying char array      cout      < <     'The new copied character array is : '  ;      cout      < <     ch      < <     endl  ;      // Displaying strings before swapping      cout      < <     'The 1st string before swapping is : '  ;      cout      < <     str1      < <     endl  ;      cout      < <     'The 2nd string before swapping is : '  ;      cout      < <     str2      < <     endl  ;      // using swap() to swap string content      str1  .  swap  (  str2  );      // Displaying strings after swapping      cout      < <     'The 1st string after swapping is : '  ;      cout      < <     str1      < <     endl  ;      cout      < <     'The 2nd string after swapping is : '  ;      cout      < <     str2      < <     endl  ;      return     0  ;   }   

산출
The new copied character array is : geeksforgeeks The 1st string before swapping is : geeksforgeeks is for geeks The 2nd string before swapping is : geeksforgeeks rocks The 1st string after swapping is : geeksforgeeks rocks The 2nd string after swapping is : geeksforgeeks is for geeks 


꼭 읽어야 할 내용: C++ 문자열 클래스 및 해당 응용 프로그램