Why prefer std::string over char*?
Automatic memory management, bounds-safe operations, and rich API reduce errors.
Master the C++ string class with comprehensive examples, built-in functions reference table, and advanced string manipulation techniques.
String Initialization
Modify & Transform
Find & Replace
Compare Strings
Text is everywhere in programs—names, logs, JSON, files. Compare C-style char arrays with std::string and learn safe, expressive string operations used in real C++ code.
String bugs (buffer overflows, off-by-one) are historic security issues. Modern std::string skills are mandatory for interviews.
C++ provides a powerful string class in the <string> header that makes string handling much easier than C-style character arrays. The string class manages memory automatically and provides numerous member functions for string manipulation.
at()#include <string> // string class
#include <iostream> // Input/output
#include <cctype> // Character functions
#include <algorithm> // STL algorithms
#include <sstream> // String streams
C++ string: std::string str = "Hello"; (Safe, feature-rich)
C-style: char str[] = "Hello"; (Manual memory, limited functions)
string s = "Hello";string s = "Hi";
s += " World";string s = "Hello";
cout << s.length(); // 5string s = "Hello";
cout << s[0]; // 'H'string a = "hi", b = "hi";
if (a == b) cout << "Equal";string line;
getline(cin, line);The following table provides a comprehensive reference of all C++ string class member functions with examples and descriptions:
| Function | Syntax | Description | Return Type |
|---|---|---|---|
| Creation & Initialization | |||
| Constructor | string() |
Default constructor, creates empty string | constructor |
| Constructor | string(const char* s) |
From C-style string | constructor |
| Constructor | string(size_t n, char c) |
Creates string of n copies of character c | constructor |
| Copy Constructor | string(const string& str) |
Copy constructor | constructor |
| Capacity Functions | |||
length() |
str.length() |
Returns number of characters in string | size_t |
size() |
str.size() |
Same as length() | size_t |
capacity() |
str.capacity() |
Returns size of allocated storage | size_t |
empty() |
str.empty() |
Returns true if string is empty | bool |
resize() |
str.resize(n, c) |
Resizes string to n characters | void |
reserve() |
str.reserve(n) |
Requests capacity change | void |
shrink_to_fit() |
str.shrink_to_fit() |
Reduces capacity to fit size (C++11) | void |
| Element Access | |||
operator[] |
str[index] |
Access character (no bounds checking) | char& |
at() |
str.at(index) |
Access character with bounds checking | char& |
front() |
str.front() |
Returns first character (C++11) | char& |
back() |
str.back() |
Returns last character (C++11) | char& |
| Modification Functions | |||
append() |
str.append(s) |
Appends string to the end | string& |
push_back() |
str.push_back(c) |
Appends character to the end | void |
pop_back() |
str.pop_back() |
Removes last character (C++11) | void |
insert() |
str.insert(pos, s) |
Inserts string at position pos | string& |
erase() |
str.erase(pos, len) |
Erases characters | string& |
replace() |
str.replace(pos, len, s) |
Replaces portion of string | string& |
clear() |
str.clear() |
Clears the string | void |
swap() |
str1.swap(str2) |
Swaps contents with another string | void |
| String Operations | |||
c_str() |
str.c_str() |
Returns C-style string (const char*) | const char* |
data() |
str.data() |
Returns pointer to character array | const char* |
copy() |
str.copy(buf, len, pos) |
Copies characters to char array | size_t |
substr() |
str.substr(pos, len) |
Returns substring | string |
| Search Functions | |||
find() |
str.find(s, pos) |
Find content in string | size_t |
rfind() |
str.rfind(s, pos) |
Find last occurrence | size_t |
find_first_of() |
str.find_first_of(s, pos) |
Find character from set | size_t |
find_last_of() |
str.find_last_of(s, pos) |
Find last character from set | size_t |
find_first_not_of() |
str.find_first_not_of(s, pos) |
Find character not in set | size_t |
find_last_not_of() |
str.find_last_not_of(s, pos) |
Find last character not in set | size_t |
| Comparison Functions | |||
compare() |
str.compare(s) |
Compares two strings | int |
operator== |
str1 == str2 |
Equality operator | bool |
operator!= |
str1 != str2 |
Inequality operator | bool |
operator< |
str1 < str2 |
Less than operator | bool |
operator> |
str1 > str2 |
Greater than operator | bool |
| Iterators | |||
begin() |
str.begin() |
Returns iterator to beginning | iterator |
end() |
str.end() |
Returns iterator to end | iterator |
rbegin() |
str.rbegin() |
Returns reverse iterator | reverse_iterator |
rend() |
str.rend() |
Returns reverse iterator end | reverse_iterator |
cbegin() |
str.cbegin() |
Returns const iterator (C++11) | const_iterator |
cend() |
str.cend() |
Returns const iterator end (C++11) | const_iterator |
C++ strings can be created and initialized in multiple ways. Understanding these methods is essential for effective string handling.
string s1;string s2 = "C++";string s3(s2);string s = "Hello World";
string sub = s.substr(0, 5);string s(5, '*'); // "*****"const char* c = "Hi";
string s(c);string s1; // Empty
string s2 = "text"; // From literal
string s3("text"); // Constructor
string s4 = s2; // Copy
string s5(5, 'x'); // Repeat char
string s6(s2, 1, 3); // Substring
string s7("text", 2); // First n chars
string s8{'a', 'b', 'c'}; // Initializer list
auto s9 = "text"s; // Literal suffix (C++14)
C++ provides numerous functions to modify string content. These functions allow you to append, insert, erase, replace, and transform strings.
string s = "Hi";
s.append(" there");string s = "Hello";
s.insert(5, " World");string s = "Hello";
s.erase(0, 1); // "ello"string s = "Hello";
s.replace(0, 5, "Hi");string s = "Hi";
s.clear(); // ""string s = "Hi";
s.push_back('!');reserve() before building large strings with multiple append operations. This reduces memory reallocations and improves performance significantly.
C++ provides powerful search functions to find substrings, characters, and patterns within strings. These functions return the position or string::npos if not found.
string s = "Hello World";
size_t p = s.find("World");if (s.find("x") == string::npos)
cout << "Not found";size_t p = s.find('o');size_t p = s.rfind('o');size_t p = s.find_first_of("aeiou");// C++23: s.contains("World")
bool ok = s.find("World") != string::npos;size_t position if foundstring::nposstring::npos is a static constant of type size_t with value -1string::npos before using the resultC++ provides multiple ways to compare strings, including relational operators and the compare() member function for more detailed comparisons.
if (s1 == s2) cout << "Equal";if (s1 < s2) cout << "s1 first";if (s1.compare(s2) == 0)if (s1.compare(s2) < 0)// use transform + tolower per charstrcmp(cstr1, cstr2); // C strings"100" < "20" returns true because '1' comes before '2' in ASCII. Convert to numbers for numerical comparison.
C++ strings can be converted to other types and combined with other C++ features for powerful text processing.
int n = stoi("42");string s = to_string(100);double d = stod("3.14");string s = "Hi";
const char* c = s.c_str();stringstream ss;
ss << 42; ss >> n;for (char c : s) cout << c;reserve() before building large strings with multiple append operationsshrink_to_fit() after building to minimize memory usageconst reference to avoid unnecessary copiesstring_view (C++17) for read-only string parameters+ in loopsstd::string instead of C-style stringsconst std::string& for read-only accessreserve() when building large stringsfind() over manual character-by-character searchempty() instead of size() == 0string::npos properly in search operationsstd::string_view (C++17) for read-only parametersstring::npos after find()[] operator without bounds checking#include <string>c_str() pointersstring s = "Hello"; // not char[]void print(const string& s);string s; s.reserve(100);// BAD: strcat on small buffer
// GOOD: s += "text";if (s.find("x") != string::npos)getline(cin, line); // not cin >>Automatic memory management, bounds-safe operations, and rich API reduce errors.
Use == for std::string content comparison; strcmp for C-strings.
A sentinel value meaning ‘not found’ returned by find operations.