C++

C++ std::string 클래스 총정리

김구티2 2024. 6. 17. 19:58

1. std:: string의 개념

C++는 일련의 문자를 클래스의 객체로 나타내는 방법을 갖고 있다. 이 클래스는 std:: string이라고 불린다. 문자열 클래스는 문자를 바이트의 시퀀스로 저장하고 단일 바이트 문자에 대한 접근을 허용하는 기능을 한다.

 

문자열(String)과 문자 배열(Character Array)의 차이가 헷갈릴 수 있는데, 이를 정리하면 다음과 같다.

String Character Array
문자열은 문자 스트림으로 표현되는 개체를 정의하는 클래스다. 문자 배열은 단순히 Null 문자로 종료할 수 있는 문자 배열이다.
문자열의 경우 메모리가 동적으로 할당된다. 더 많은 메모리가 필요할 때 실행 시간에 할당될 수 있다. 그리고 메모리가 미리 할당되지 않으므로 메모리가 낭비되지 않는다. 문자 배열의 크기를 정적으로 할당해야 하며, 필요한 경우 실행 시간에 더 많은 메모리를 할당할 수 없다. 그리고 사용되지 않은 할당된 메모리는 낭비된다.
문자열이 개체로 표현되기 때문에 배열 붕괴가 발생하지 않는다. 배열 붕괴의 위험이 있다.
문자열은 문자 배열에 비해 구현 속도가 느리다. std:: 문자열보다 문자 배열 구현이 빠르다.
문자열 클래스는 문자열에서 다양한 연산을 허용하는 여러 기능을 정의한다.
문자 배열은 문자열을 조작할 수 있는 내장 기능을 많이 제공하지 않는다.

2. 문자열 작동

① INPUT 함수

getline(): 이 기능은 사용자가 입력한 문자 스트림을 객체 메모리에 저장하는 데 사용된다.

push_back(): 문자열 끝에 문자를 입력할 때 사용하는 기능이다.

pop_back(): C++11( 문자열의 경우)에서 도입된 이 함수는 문자열에서 마지막 문자를 삭제하는 데 사용된다.

 

예시:

// C++ Program to demonstrate the working of 
// getline(), push_back() and pop_back() 
#include <iostream> 
#include <string> // 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 : 

 

② CAPACITY 함수

capacity(): 이 함수는 문자열에 할당된 용량을 반환하는데, 문자열의 크기와 같거나 그 이상일 수 있다. 문자열에 새 문자를 추가할 때 작업을 효율적으로 수행할 수 있도록 추가 공간이 할당된다.
resize(): 이 기능은 문자열의 크기를 변경하고, 크기를 늘리거나 줄일 수 있다.
length(): 이 함수는 문자열의 길이를 구한다.
shrink_to_fit(): 이 함수는 문자열의 용량을 줄이고 문자열의 최소 용량과 같게 만든다. 이 작업은 문자를 더 이상 추가할 필요가 없다고 확신한다면 추가 메모리를 절약하는 데 유용하다.

 

예시:

// C++ Program to demonstrate the working of 
// capacity(), resize() and shrink_to_fit() 
#include <iostream> 
#include <string> // for string class 
using namespace std; 

// Driver Code 
int main() 

     // Initializing string 
     string str = "guti is for gutilog"

     // 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 : guti is for gutilog
The string after resize operation is : gutilog
The capacity of string is : 19
The length of the string is :7
The new capacity after shrinking is : 7

 

③ Iterator 함수

begin(): 이 함수는 반복자를 문자열의 처음으로 반환한다.
end(): 이 함수는 반복자를 문자열 끝 옆으로 반환한다.
rbegin(): 이 함수는 문자열의 끝을 가리키는 역방향 반복자를 반환한다.
rend(): 이 함수는 문자열 시작의 이전을 가리키는 역방향 반복자를 반환한다.
cbegin():  이 함수는 문자열의 시작을 가리키는 상수 반복자를 반환하므로 문자열이 가리키는 내용을 수정하는 데 사용할 수 없다.
cend(): 이 함수는 문자열의 다음 끝을 가리키는 상수 반복자를 반환하므로 문자열이 가리키는 내용을 수정하는 데 사용할 수 없다.
crbegin(): 이 함수는 문자열의 끝을 가리키는 일정한 역방향 반복자를 반환하므로 문자열이 가리키는 내용을 수정하는 데 사용할 수 없다.
crend(): 이 함수는 문자열 시작의 이전을 가리키는 일정한 역방향 반복자를 반환하므로 문자열이 가리키는 내용을 수정하는 데 사용할 수 없다.

 

* 여기서 알고리즘은 다음과 같다.

⑴ 문자열(String) 선언

⑵ 모든 유형의 반복자를 사용해 문자열 반복

⑶ 문자열의 요소 수정

⑷ 모든 반복 표시

 

예시:

// C++ Program to demonstrate the working of 
// begin(), end(), rbegin(), rend(), cbegin(), cend(), crbegin(), crend() 
#include <iostream> 
#include <string> // for string class 
using namespace std; 

// Driver Code 
int main() 

     // Initializing string` 
     string str = "gutilogda"

     // 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 = "gutilogda"
     // 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 = "gutilogda"
     //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 = "gutilogda"
     //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; 


출력:

Str:gutilog
The string using forward iterators is : gutilogda
The reverse string using reverse iterators is : gutilogda
The string using constant forward iterator is : autiloadg
The reverse string using constant reverse iterator is : adgolitug

 

④ Manipulating 함수

copy(“char array”, len, pos): 이 함수는 인수에 언급된 대상 문자 배열의 부분 문자열을 복사한다. 복사를 시작하려면 문자열에서 3개의 인수, 대상 문자 배열, 복사할 길이, 시작 위치가 필요하다.
swap(): 이 함수는 한 문자열을 다른 문자열과 스왑한다.

 

예시:

// C++ Program to demonstrate the working of 
// copy() and swap() 
#include <iostream> 
#include <string> // for string class 
using namespace std; 

// Driver Code 
int main() 

     // Initializing 1st string 
     string str1 = "gutilog is for guti"

     // Declaring 2nd string 
     string str2 = "gutilog winner"

     // Declaring character array 
     char ch[80]; 

     // using copy() to copy elements into char array 
     // copies "gutilog" 
     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 : gutilog
The 1st string before swapping is : gutilog is for guti
The 2nd string before swapping is : gutilog winner
The 1st string after swapping is : gutilog winner
The 2nd string after swapping is : gutilog is for guti

 

728x90