basic_string

basic_string (문자열 클래스 템플릿)

std::basic_string은 문자형 객체의 시퀀스를 저장하고 조작하는 클래스 템플릿이에요. 이 타입은 특정 문자 타입이나 그 타입에 대한 연산의 성격에 의존하지 않아요. 연산의 정의는 Traits 템플릿 매개변수, 즉 std::char_traits의 특수화나 호환 가능한 traits 클래스를 통해 제공돼요.

출처: cppreference

본문

정의

<string> 헤더에 정의됨
template < class CharT , class Traits = std :: char_traits < CharT > , class Allocator = std :: allocator < CharT > > class basic_string ; (1)
namespace pmr { template < class CharT , class Traits = std :: char_traits < CharT > > using basic_string = std :: basic_string < CharT , Traits , std :: pmr :: polymorphic_allocator < CharT >> ; } (2) (C++17부터)

basic_string 클래스 템플릿은 TrivialType 및 StandardLayoutType의 비배열 객체인 문자형 객체의 시퀀스를 저장하고 조작해요. 이 클래스는 문자 타입이나 그 타입에 대한 연산의 성격에 의존하지 않아요. 연산의 정의는 Traits 템플릿 매개변수, 즉 std::char_traits의 특수화 또는 호환 가능한 traits 클래스를 통해 제공돼요.

basic_string의 요소들은 연속적으로 저장돼요. 즉, basic_string s에 대해 [0, s.size()) 범위의 모든 n에서 &*(s.begin() + n) == &*s.begin() + n이 성립하고, *(s.begin() + s.size())CharT() 값(널 종결자)을 가져요 (C++11부터). 또는 동등하게, s[0]에 대한 포인터는 CharT의 배열(C++11 이전) 또는 널 종결 배열(C++11부터)의 첫 번째 요소를 기대하는 함수에 전달될 수 있어요.

std::basic_string은 AllocatorAwareContainer(요소의 생성/파괴에 맞춤형 construct/destroy가 사용되지 않는다는 점 제외), SequenceContainer, 그리고 (C++17부터) ContiguousContainer의 요구 사항을 충족해요.

Traits::char_typeCharT가 아니거나 Allocator::value_typeCharT가 아니면 프로그램은 ill-formed예요.

std::basic_string의 모든 멤버 함수는 constexpr이에요. 상수 표현식 평가에서 std::basic_string 객체를 생성하고 사용할 수 있어요. 하지만 constexpr std::basic_string 변수를 정의하는 것은 일반적으로 오류예요. 상수 평가에서는 동적으로 할당된 저장 공간이 동일한 평가에서 해제되어야 하는데, std::basic_string의 초기화에서는 보통 그렇지 않기 때문이에요. (C++20부터)

일반적인 문자 타입에 대한 여러 typedef가 제공돼요:

<string> 헤더에 정의됨
타입 정의
std::string std::basic_string<char>
std::wstring std::basic_string<wchar_t>
std::u8string (C++20) std::basic_string<char8_t>
std::u16string (C++11) std::basic_string<char16_t>
std::u32string (C++11) std::basic_string<char32_t>
std::pmr::string (C++17) std::pmr::basic_string<char>
std::pmr::wstring (C++17) std::pmr::basic_string<wchar_t>
std::pmr::u8string (C++20) std::pmr::basic_string<char8_t>
std::pmr::u16string (C++17) std::pmr::basic_string<char16_t>
std::pmr::u32string (C++17) std::pmr::basic_string<char32_t>

템플릿 매개변수

CharT - 문자 타입
Traits - 문자 타입에 대한 연산을 지정하는 traits 클래스
Allocator - 내부 저장 공간을 할당하는 데 사용되는 할당자 타입

반복자 무효화

basic_string의 요소를 참조하는 참조자, 포인터, 반복자는 비-const basic_string에 대한 참조를 인자로 받는 표준 라이브러리 함수(예: std::getline, std::swap, operator>>)를 호출하거나, 비-const 멤버 함수를 호출할 때 무효화될 수 있어요. 단, operator[], at, data, front, back, begin, rbegin, end, rend는 예외예요.

중첩 타입

타입 정의
traits_type Traits
value_type CharT
allocator_type Allocator
size_type Allocator::size_type (C++11 이전)
std::allocator_traits<Allocator>::size_type (C++11부터)
difference_type Allocator::difference_type (C++11 이전)
std::allocator_traits<Allocator>::difference_type (C++11부터)
reference value_type&
const_reference const value_type&
pointer Allocator::pointer (C++11 이전)
std::allocator_traits<Allocator>::pointer (C++11부터)
const_pointer Allocator::const_pointer (C++11 이전)
std::allocator_traits<Allocator>::const_pointer (C++11부터)
iterator value_type에 대한 LegacyRandomAccessIterator 및 LegacyContiguousIterator (C++20 이전)
value_type에 대한 LegacyRandomAccessIterator, contiguous_iterator, ConstexprIterator (C++20부터)
const_iterator const value_type에 대한 LegacyRandomAccessIterator 및 LegacyContiguousIterator (C++20 이전)
const value_type에 대한 LegacyRandomAccessIterator, contiguous_iterator, ConstexprIterator (C++20부터)
reverse_iterator std::reverse_iterator<iterator>
const_reverse_iterator std::reverse_iterator<const_iterator>

데이터 멤버

constexpr size_type npos [static] 특수 값 size_type(-1)이며, 정확한 의미는 문맥에 따라 달라져요.

멤버 함수

(constructor) basic_string을 생성해요 (public member function)
(destructor) 문자열을 파괴하고, 사용된 내부 저장 공간을 해제해요 (public member function)
operator= 문자열에 값을 할당해요 (public member function)
assign 문자열에 문자를 할당해요 (public member function)
assign_range (C++23) 문자열에 문자 범위를 할당해요 (public member function)
get_allocator 연관된 할당자를 반환해요 (public member function)
요소 접근
at 경계 검사와 함께 지정된 문자에 접근해요 (public member function)
operator[] 지정된 문자에 접근해요 (public member function)
front (DR*) 첫 번째 문자에 접근해요 (public member function)
back (DR*) 마지막 문자에 접근해요 (public member function)
data 문자열의 첫 번째 문자에 대한 포인터를 반환해요 (public member function)
c_str 문자열의 수정 불가능한 표준 C 문자 배열 버전을 반환해요 (public member function)
operator basic_string_view (C++17) 전체 문자열에 대한 수정 불가능한 basic_string_view를 반환해요 (public member function)
반복자
begin, cbegin (C++11) 시작을 가리키는 반복자를 반환해요 (public member function)
end, cend (C++11) 끝을 가리키는 반복자를 반환해요 (public member function)
rbegin, crbegin (C++11) 시작을 가리키는 역방향 반복자를 반환해요 (public member function)
rend, crend (C++11) 끝을 가리키는 역방향 반복자를 반환해요 (public member function)
용량
empty 문자열이 비어 있는지 확인해요 (public member function)
size, length 문자 수를 반환해요 (public member function)
max_size 최대 문자 수를 반환해요 (public member function)
reserve 저장 공간을 예약해요 (public member function)
capacity 현재 할당된 저장 공간에 보관할 수 있는 문자 수를 반환해요 (public member function)
shrink_to_fit (DR*) 사용하지 않는 메모리를 해제하여 메모리 사용량을 줄여요 (public member function)
수정자
clear 내용을 지워요 (public member function)
insert 문자를 삽입해요 (public member function)
insert_range (C++23) 문자 범위를 삽입해요 (public member function)
erase 문자를 제거해요 (public member function)
push_back 끝에 문자를 추가해요 (public member function)
pop_back (DR*) 마지막 문자를 제거해요 (public member function)
append 끝에 문자를 추가해요 (public member function)
append_range (C++23) 끝에 문자 범위를 추가해요 (public member function)
operator+= 끝에 문자를 추가해요 (public member function)
replace 문자열의 지정된 부분을 교체해요 (public member function)
replace_with_range (C++23) 문자열의 지정된 부분을 문자 범위로 교체해요 (public member function)
copy 문자를 복사해요 (public member function)
resize 저장된 문자 수를 변경해요 (public member function)
resize_and_overwrite (C++23) 저장된 문자 수를 변경하고 사용자 제공 연산으로 불확정 내용을 덮어쓸 수 있어요 (public member function)
swap 내용을 교환해요 (public member function)
검색
find 주어진 부분 문자열의 첫 번째 발생을 찾아요 (public member function)
rfind 부분 문자열의 마지막 발생을 찾아요 (public member function)
find_first_of 문자의 첫 번째 발생을 찾아요 (public member function)
find_first_not_of 문자가 없는 첫 번째 위치를 찾아요 (public member function)
find_last_of 문자의 마지막 발생을 찾아요 (public member function)
find_last_not_of 문자가 없는 마지막 위치를 찾아요 (public member function)
연산
compare 두 문자열을 비교해요 (public member function)
starts_with (C++20) 문자열이 주어진 접두사로 시작하는지 확인해요 (public member function)
ends_with (C++20) 문자열이 주어진 접미사로 끝나는지 확인해요 (public member function)
contains (C++23) 문자열이 주어진 부분 문자열이나 문자를 포함하는지 확인해요 (public member function)
substr 부분 문자열을 반환해요 (public member function)
subview (C++26) 하위 뷰를 반환해요 (public member function)

비멤버 함수

operator+ 두 문자열, 문자열과 char, 또는 문자열과 string_view를 연결해요 (function template)
operator==, operator!=, operator<, operator>, operator<=, operator>=, operator<=> (C++20에서 일부 제거됨) 두 문자열을 사전식으로 비교해요 (function template)
std::swap(std::basic_string) std::swap 알고리즘을 특수화해요 (function template)
erase(std::basic_string), erase_if(std::basic_string) (C++20) 특정 기준을 충족하는 모든 요소를 지워요 (function template)
입출력
operator<<, operator>> 문자열에 대한 스트림 입력과 출력을 수행해요 (function template)
getline I/O 스트림에서 문자열로 데이터를 읽어요 (function template)
숫자 변환
stoi, stol, stoll (C++11) 문자열을 부호 있는 정수로 변환해요 (function)
stoul, stoull (C++11) 문자열을 부호 없는 정수로 변환해요 (function)
stof, stod, stold (C++11) 문자열을 부동소수점 값으로 변환해요 (function)
to_string (C++11) 정수 또는 부동소수점 값을 문자열로 변환해요 (function)
to_wstring (C++11) 정수 또는 부동소수점 값을 wstring으로 변환해요 (function)

리터럴

인라인 네임스페이스 std::literals::string_literals에 정의됨
operator""s (C++14)

헬퍼 클래스

std::hash<std::basic_string> (C++11) 문자열에 대한 해시 지원 (class template specialization)

연역 가이드 (C++17부터)

참고 사항

C++23 이전에는 std::basic_string의 요소를 생성하거나 파괴할 때 맞춤형 construct/destroy를 사용해야 했지만, 모든 구현은 기본 메커니즘만 사용했어요. 이 요구 사항은 기존 관행에 맞게 P1072R10으로 수정되었어요.

기능 테스트 매크로 표준 기능
__cpp_lib_string_udls 201304L (C++14) 문자열 타입에 대한 사용자 정의 리터럴
__cpp_lib_starts_ends_with 201711L (C++20) starts_with, ends_with
__cpp_lib_constexpr_string 201907L (C++20) std::basic_string에 대한 constexpr
__cpp_lib_char8_t 201907L (C++20) std::u8string
__cpp_lib_erase_if 202002L (C++20) erase, erase_if
__cpp_lib_string_contains 202011L (C++23) contains
__cpp_lib_string_resize_and_overwrite 202110L (C++23) resize_and_overwrite
__cpp_lib_containers_ranges 202202L (C++23) 컨테이너 호환 범위를 받는 생성, 삽입, 교체 멤버 함수

예제

#include <iostream>
#include <string>

int main()
{
    using namespace std::literals;
    
    // Creating a string from const char*
    std::string str1 = "hello";
    
    // Creating a string using string literal
    auto str2 = "world"s;
    
    // Concatenating strings
    std::string str3 = str1 + " " + str2;
    
    // Print out the result
    std::cout << str3 << '\n';
    
    std::string::size_type pos = str3.find(" ");
    str1 = str3.substr(pos + 1); // the part after the space
    str2 = str3.substr(0, pos);  // the part till the space
    
    std::cout << str1 << ' ' << str2 << '\n';
    
    // Accessing an element using subscript operator[]
    std::cout << str1[0] << '\n';
    str1[0] = 'W';
    std::cout << str1 << '\n';
}

출력:

hello world
world hello
w
World

결함 보고서

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.

DR 적용 대상 발표된 동작 올바른 동작
LWG 530 C++98 basic_string 요소의 저장 공간 연속성이 LWG259에 의해 실수로 요구되지 않게 됨 다시 요구됨
LWG 2861 C++98 value_typeTraits::char_type이었음 CharT로 변경됨
LWG 2994 (P1148R0) C++98 Traits::char_typeAllocator::char_type 중 하나라도 CharT와 다르면 동작이 미정의였음 이 경우 프로그램은 ill-formed임
  • Traits::char_type 경우는 P1148R0에서 수정되었어요.

같이 보기

basic_string_view (C++17) 읽기 전용 문자열 뷰 (class template)

외부 링크

C++ 문자열 처리

더 알아보기 (Learn more)

cppreference