C++ Strings Complete Guide
Functions Reference

C++ Strings: Complete Guide with Built-in Functions

Master the C++ string class with comprehensive examples, built-in functions reference table, and advanced string manipulation techniques.

Creation

String Initialization

Manipulation

Modify & Transform

Search

Find & Replace

Comparison

Compare Strings

C++ Tutorial · 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.

What you will learn

  • Create and manipulate std::string objects
  • Use C-string functions safely with char buffers
  • Compare, concatenate, and search substrings
  • Convert between strings and numbers
  • Choose string vs string_view for performance

Why this topic matters

String bugs (buffer overflows, off-by-one) are historic security issues. Modern std::string skills are mandatory for interviews.

Key terms & indexing

C++ string std::string C++ string functions cstring C++

Introduction to C++ Strings

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.

Key Advantages
  • Automatic memory management
  • Rich set of member functions
  • Operator overloading (+, =, ==, etc.)
  • Compatible with STL algorithms
  • Bounds checking with at()
  • Iterators for traversal
Essential Headers
#include <string>    // string class
#include <iostream>  // Input/output
#include <cctype>    // Character functions
#include <algorithm> // STL algorithms
#include <sstream>   // String streams

C++ string vs C-style strings

C++ string: std::string str = "Hello"; (Safe, feature-rich)
C-style: char str[] = "Hello"; (Manual memory, limited functions)

Examples

1. Declare string
string s = "Hello";
2. Concatenate
string s = "Hi";
s += " World";
3. Length
string s = "Hello";
cout << s.length();  // 5
4. Access char
string s = "Hello";
cout << s[0];  // 'H'
5. Compare
string a = "hi", b = "hi";
if (a == b) cout << "Equal";
6. Input line
string line;
getline(cin, line);

Complete C++ String Functions Reference

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

1. String Creation and Initialization

C++ strings can be created and initialized in multiple ways. Understanding these methods is essential for effective string handling.

Examples

1. Empty string
string s1;
2. From literal
string s2 = "C++";
3. Copy construct
string s3(s2);
4. Substring
string s = "Hello World";
string sub = s.substr(0, 5);
5. Repeat chars
string s(5, '*');  // "*****"
6. From C-string
const char* c = "Hi";
string s(c);
Initialization Cheat Sheet
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)

2. String Manipulation Functions

C++ provides numerous functions to modify string content. These functions allow you to append, insert, erase, replace, and transform strings.

Examples

1. append()
string s = "Hi";
s.append(" there");
2. insert()
string s = "Hello";
s.insert(5, " World");
3. erase()
string s = "Hello";
s.erase(0, 1);  // "ello"
4. replace()
string s = "Hello";
s.replace(0, 5, "Hi");
5. clear()
string s = "Hi";
s.clear();  // ""
6. push_back()
string s = "Hi";
s.push_back('!');
Performance Tip: Use reserve() before building large strings with multiple append operations. This reduces memory reallocations and improves performance significantly.

4. String Comparison Functions

C++ provides multiple ways to compare strings, including relational operators and the compare() member function for more detailed comparisons.

Examples

1. == operator
if (s1 == s2) cout << "Equal";
2. < lexicographic
if (s1 < s2) cout << "s1 first";
3. compare() == 0
if (s1.compare(s2) == 0)
4. compare < 0
if (s1.compare(s2) < 0)
5. Case-insensitive
// use transform + tolower per char
6. strcmp C-style
strcmp(cstr1, cstr2);  // C strings
Important: String comparison is lexicographical (dictionary order), not numerical. For example, "100" < "20" returns true because '1' comes before '2' in ASCII. Convert to numbers for numerical comparison.

5. String Conversion and Advanced Operations

C++ strings can be converted to other types and combined with other C++ features for powerful text processing.

Examples

1. stoi
int n = stoi("42");
2. to_string
string s = to_string(100);
3. stod
double d = stod("3.14");
4. c_str()
string s = "Hi";
const char* c = s.c_str();
5. stringstream
stringstream ss;
ss << 42; ss >> n;
6. Range-for chars
for (char c : s) cout << c;
String Performance Tips:
  1. Use reserve() before building large strings with multiple append operations
  2. Use shrink_to_fit() after building to minimize memory usage
  3. Pass strings by const reference to avoid unnecessary copies
  4. Use string_view (C++17) for read-only string parameters
  5. Avoid repeated concatenation with + in loops

6. Best Practices and Common Mistakes

Best Practices
  • Use std::string instead of C-style strings
  • Pass strings by const std::string& for read-only access
  • Use reserve() when building large strings
  • Prefer find() over manual character-by-character search
  • Use empty() instead of size() == 0
  • Handle string::npos properly in search operations
  • Use std::string_view (C++17) for read-only parameters
Common Mistakes
  • Not checking string::npos after find()
  • Using [] operator without bounds checking
  • Forgetting to #include <string>
  • Memory leaks with c_str() pointers
  • Inefficient string concatenation in loops
  • Case-sensitive comparison when case-insensitive is needed
  • Assuming ASCII encoding for international text

Examples

1. Prefer string
string s = "Hello";  // not char[]
2. const ref param
void print(const string& s);
3. reserve size
string s; s.reserve(100);
4. Avoid C strcat
// BAD: strcat on small buffer
// GOOD: s += "text";
5. Check find result
if (s.find("x") != string::npos)
6. Use getline
getline(cin, line);  // not cin >>

Frequently asked questions

Why prefer std::string over char*?

Automatic memory management, bounds-safe operations, and rich API reduce errors.

How do I compare two strings?

Use == for std::string content comparison; strcmp for C-strings.

What is std::string::npos?

A sentinel value meaning ‘not found’ returned by find operations.