C++ std::string Complete Guide: Operations, Split, Trim & Performance
이 글의 핵심
Hands-on reference for C++ string basics, common algorithms, pitfalls, and performance tips.
std::string is a contiguous character sequence—the same “resizable array” story as in arrays and lists.
Basics
Declaration and initialization
#include <string>
#include <iostream>
using namespace std;
string s1 = "Hello";
string s2("World");
string s3 = s1;
string s4(5, 'A');
Concatenation
Use +, +=, and append() as in the Korean article.
Comparison
==, <, and compare() for lexicographic order.
Size and access
length(), size(), operator[], at() with bounds checking.
Substrings
substr(pos, len) and substr(pos) to end.
Search
find, rfind, find_first_of, etc.; compare position to string::npos.
Replace
replace(pos, len, new); for global substring replace, loop find + replace or use algorithms.
Insert / erase / clear
insert, erase, clear.
Practical examples
Split (CSV)
Use stringstream + getline or find / substr — patterns match the source post.
Trim
Erase from first non-space to last non-space using find_if on begin/rbegin.
Case and validation
transform with toupper/tolower; simple email / numeric checks as in original.
Common pitfalls
- C strings: string literals are not writable
char*; useconst char*orstd::string. npos: usesize_t/auto, notint, when comparingfindresults.- Concatenation in loops:
reserveorstringstream.
Performance
Prefer const string& parameters, reserve when size is known, and measure before low-level tricks.
FAQ
Beginner-friendly; real-world usage high; compare to other languages; learning path; common mistakes (uninitialized state, complexity, exceptions) — aligned with Korean article.
Related posts
- C++ STL vector
- C++ set / unordered_set
- C++ map / unordered_map
Keywords
std::string, string_view, substr, find, replace, SSO, C++, STL