std::string
개요
std::string
은 C++ 표준 라이브러리에서 제공하는 문자열 클래스로, 문자열 조작을 위한 다양한 기능을 제공합니다. 메모리 관리를 자동으로 처리하며, 안전하고 편리한 문자열 처리가 가능합니다.
C++ 버전별 주요 키워드 도입 시기
- C++98: 기본
std::string
클래스 도입 - C++11: 이동 생성자/대입 연산자,
shrink_to_fit()
등 추가 - C++17:
string_view
와의 상호작용 추가, 비멤버std::size()
등 추가 - C++20:
starts_with()
,ends_with()
메서드 추가
내용 설명
std::string
은 다음과 같은 주요 특징을 가집니다:
- 동적 메모리 관리: 문자열 길이에 따라 자동으로 메모리 할당/해제
- 문자열 조작: 다양한 멤버 함수를 통한 문자열 검색, 삽입, 삭제, 교체 등
- 반복자 지원: STL 알고리즘과의 호환성
- 문자열 변환: 숫자와 문자열 간 변환 기능 제공
- SSO(Short String Optimization): 짧은 문자열의 경우 힙 할당 없이 객체 내부에 저장
예제 코드
#include <iostream>
#include <string>
#include <iomanip>
void print_found_idx(const std::size_t idx, const std::string &func_name)
{
std::cout << "Function: " << func_name << '\n';
if (idx != std::string::npos)
std::cout << "Found at idx: " << idx << '\n';
else
std::cout << "Not Found!" << idx << '\n';
}
int main()
{
// 문자열 생성 및 기본 정보
auto text = std::string{"Hello people!"};
std::cout << text << '\n';
std::cout << "Is empty: " << text.empty() << '\n';
std::cout << "Length: " << text.length() << '\n';
// 문자열 검색
const auto search_str1 = "eo";
const auto idx1 = text.find(search_str1, 5);
print_found_idx(idx1, "find");
// 역방향 검색
const auto search_str2 = "e";
const auto idx2 = text.rfind(search_str2);
print_found_idx(idx2, "rfind");
// 문자열 비교
auto s1 = std::string{"Jann"};
auto s2 = std::string{"Jan"};
std::cout << "s1 == s2: " << std::boolalpha << (s1 == s2) << '\n';
const auto compared = s1.compare(s2);
std::cout << "s1.compare(s2): " << compared << '\n';
// 문자열 수정
const auto search_str = "nn";
const auto idx = s1.find(search_str);
if (idx != std::string::npos)
s1.replace(idx, 2, "n");
std::cout << s1 << '\n';
// 부분 문자열 추출
const auto sub_str = s1.substr(2, 3);
std::cout << sub_str << '\n';
// 숫자 -> 문자열 변환
auto si = std::to_string(42); // si="42"
auto sl = std::to_string(42L); // sl="42"
auto su = std::to_string(42u); // su="42"
// 문자열 -> 정수 변환
auto i1 = std::stoi("42"); // i1 = 42
auto i2 = std::stoi("101010", nullptr, 2); // i2 = 42 (이진수)
auto i3 = std::stoi("052", nullptr, 8); // i3 = 42 (8진수)
auto i4 = std::stoi("0x2A", nullptr, 16); // i4 = 42 (16진수)
// 문자열 -> 실수 변환
auto d1 = std::stod("123.45"); // d1 = 123.45
auto d2 = std::stod("1.2345e+2"); // d2 = 123.45 (지수 표기법)
auto d3 = std::stod("0xF.6E6666p3"); // d3 = 123.45 (16진수 부동소수점)
return 0;
}
실행 결과
Hello people!
Is empty: false
Length: 13
Function: find
Not Found!18446744073709551615
Function: rfind
Found at idx: 10
s1 == s2: false
s1.compare(s2): 1
Jan
n
활용팁
- 메모리 효율: 긴 문자열을 자주 복사할 때는
std::string_view
사용을 고려하세요. - 문자열 합치기: 여러 문자열을 합칠 때는
operator+
대신std::string::append()
나+=
를 사용하면 더 효율적입니다. - 크기 예약: 많은 양의 문자열을 추가할 예정이라면
reserve()
로 미리 메모리를 할당해두세요. - SSO 활용: 짧은 문자열(일반적으로 15-22자 이내)은 SSO로 인해 추가 힙 할당 없이 처리됩니다.
- 예외 처리:
stoi
,stod
등의 변환 함수는 유효하지 않은 입력에 대해std::invalid_argument
또는std::out_of_range
예외를 던질 수 있습니다. - 널 종료 문자열:
c_str()
과data()
는 C 스타일의 널 종료 문자열을 반환합니다. C++17부터는data()
도 널 종료가 보장됩니다. - 유니코드 지원: UTF-8 문자열을 다룰 때는
std::u8string
(C++20)을 사용하는 것이 좋습니다.
'개발 > C++ (98,03,11,14,17,20,23)' 카테고리의 다른 글
Modern C++ : std::filesystem (0) | 2025.09.03 |
---|---|
Modern C++ : std::ostream & std::istream (98, 11, 17, 20) (0) | 2025.09.02 |
Modern C++ : std::string_view (17, 20) (1) | 2025.09.01 |
Modern C++ : Small String Optimization (SSO) (3) | 2025.08.31 |
Modern C++ : Custom Iterator Utilities (98, 11, 17, 20) (0) | 2025.08.29 |
Modern C++ : std::inserter (98, 11, 17) (1) | 2025.08.28 |
Modern C++ : iterators (98, 11, 17, 20) (0) | 2025.08.27 |
Modern C++ : type aliases (typedef and using) (98, 11) (0) | 2025.08.26 |