basic_string — std::basic_string
basic_string — std::basic_string
std::basic_string 클래스 템플릿은 문자 시퀀스를 저장·조작하는 문자열 타입이에요. <string> 헤더에 있어요.
std::string(char)과 std::wstring(wchar_t) 등이 이 템플릿의 특수화예요.
출처: cppreference
본문
// <string> 헤더
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
> class basic_string;
// C++17부터 pmr 버전
namespace pmr {
template<class CharT, class Traits = std::char_traits<CharT>>
using basic_string = std::basic_string<CharT, Traits,
std::pmr::polymorphic_allocator<...>>;
}
타입 별칭
| 별칭 | 타입 |
|---|---|
std::string |
basic_string<char> |
std::wstring |
basic_string<wchar_t> |
std::u8string, std::u16string, std::u32string |
UTF-8/16/32 |
사용 예
#include <string>
#include <iostream>
std::string s = "hello";
s += " world"; // "hello world"
s.push_back('!'); // "hello world!"
std::cout << s.length(); // 12
std::cout << s.substr(0, 5); // "hello"
s.replace(0, 5, "HELLO"); // "HELLO world!"
주요 연산
- 생성 — 리터럴, 복사, 이동,
std::string_view에서 생성(C++17) - 수정 —
append/+=,assign,insert,erase,replace,push_back,pop_back,clear,resize - 접근 —
operator[],at,front,back,data,c_str - 검색 —
find,rfind,find_first_of,find_first_not_of,starts_with(C++20),contains(C++23) - 비교 —
compare,==,<등 - 변환 —
c_str(),substr(),stoi/stod등 수치 변환
std::string s = "C++ 2024";
s.starts_with("C++"); // true (C++20)
s.contains("2024"); // true (C++23)
std::string sub = s.substr(4); // "2024"
int n = std::stoi("42"); // 42 (수치 변환)
std::string t = std::to_string(3.14); // "3.140000"
특징
- 동적 크기 — 필요에 따라 자동으로 확장돼요.
- 소유권 기반(값 의미론)이라 복사·이동이 잘 정의돼요.
- 할당자 지원 — 사용자 정의 메모리 정책 가능.
- 연속 메모리 — C++17부터
data()가 널 종결 보장.
// 범위 기반 문자열 처리
for (char c : s) { /* ... */ }
std::basic_string(std::string)은 C++에서 가장 널리 쓰이는 문자열 타입이에요. 풍부한 검색·수정·변환 기능을 제공해요.