C++: Strings

Use the std::string class to create, read, compare, and manipulate text with built-in methods.

Creating Strings

std::string is a class from the <string> header that manages a dynamic character sequence. It is safe, convenient, and should be preferred over C-style char arrays in modern C++.

std::string

std::string handles its own memory, it grows automatically when you append characters and frees memory when it goes out of scope.

  • Include <string> to use std::string
  • Default constructor creates an empty string: string s;
  • Initialize from a literal: string s = "Hello"; or string s("Hello");
  • Copy from another string: string s2 = s1;

Creating Strings

C++

Three ways to initialize a std::string.

String Input: cin and getline

cin >> reads one whitespace-delimited word into a string. To read an entire line including spaces, use getline(cin, s).

Reading Strings

After reading a number with cin >>, call cin.ignore() before getline to discard the leftover newline character in the buffer.

  • cin >> s reads one word, stops at whitespace
  • getline(cin, s) reads until newline, includes spaces
  • getline with delimiter: getline(cin, s, ',') reads until comma
  • Always prefer getline for user-facing string input

getline for Full-Line Input

C++

getline captures the entire line including spaces.

String Concatenation

Strings can be joined with the + operator or appended in place with +=. Both create or grow a string without worrying about buffer sizes.

Concatenation with + and +=

+ creates a new string; += appends to the existing string in place, prefer += in loops to avoid creating many temporary strings.

  • s1 + s2 produces a new string, neither s1 nor s2 is changed
  • s1 += s2 appends s2 to s1 in place
  • You can concatenate a string and a char literal: s + '!'
  • You cannot concatenate two C-string literals with +, at least one operand must be a std::string

String Concatenation

C++

Combine strings with + and extend in place with +=.

String Length

s.length() and s.size() both return the number of characters in the string as a size_t (an unsigned integer).

length() and size()

length() and size() are identical, length() exists for readability; size() matches the naming of other STL containers.

  • s.length() and s.size() return the same value
  • s.empty() returns true if the string has zero characters, faster than s.size() == 0
  • Return type is size_t (unsigned), avoid comparing it to a signed int

String Length

C++

length(), size(), and empty() on both a non-empty and an empty string.

Accessing Characters

Individual characters can be read or written using the index operator [] or the bounds-checking method at(). Use front() and back() for the first and last characters.

Character Access

Use at() in production code, it throws std::out_of_range on invalid indices; [] silently causes undefined behavior.

  • s[i], no bounds check, fast, undefined behavior if i is out of range
  • s.at(i), bounds-checked, throws if i is out of range
  • s.front(), first character (same as s[0])
  • s.back(), last character (same as s[s.size()-1])

Accessing Characters

C++

Read and modify individual characters using [] and at().

String Comparison

std::string supports the standard comparison operators ==, !=, <, >, <=, and >=. Comparison is lexicographic (alphabetical by character value).

String Comparison

std::string comparison with == and < is far cleaner than strcmp, use the operators directly.

  • s1 == s2 is true only if both strings have identical characters in identical order
  • s1 < s2 is true if s1 comes before s2 alphabetically (lexicographic order)
  • Comparison is case-sensitive: "Apple" != "apple"
  • s.compare(other) returns 0 if equal, negative if s < other, positive if s > other

String Comparison

C++

Equality and less-than operators work directly on std::string.

append()

append() adds text to the end of a string. It accepts another string, a C-string, a repeated character count, or a substring range, more flexible than += for complex cases.

append()

append() returns a reference to the modified string, so calls can be chained: s.append(a).append(b).

  • s.append(str) appends another string
  • s.append(str, pos, len) appends len characters of str starting at pos
  • s.append(n, ch) appends the character ch repeated n times
  • Equivalent to += for simple cases

append()

C++

Append a string literal and then a repeated character.

substr()

substr(pos, len) returns a new string containing len characters starting at index pos. If len is omitted, it extracts from pos to the end.

substr()

substr() does not modify the original string, it returns a brand new string.

  • s.substr(pos) extracts from pos to end
  • s.substr(pos, len) extracts len characters starting at pos
  • Throws std::out_of_range if pos is beyond the string length
  • Commonly used to split or parse strings

substr()

C++

Extract from the middle, from the start, and a fixed length.

find()

find() searches for a substring or character and returns the index of its first occurrence. If not found, it returns the special constant string::npos.

find()

Always check against string::npos before using the returned index, treating npos as a valid index will corrupt your logic.

  • s.find(str) returns the starting index of the first match
  • s.find(str, from) starts searching at index from
  • s.rfind(str) finds the last occurrence
  • Returns string::npos (a very large size_t) when not found

find()

C++

Search for a substring and guard against npos before using the result.

replace()

replace(pos, len, newStr) removes len characters starting at pos and inserts newStr in their place. The replacement string can be any length.

replace()

Combine find() and replace() to substitute the first occurrence of a word in a string.

  • s.replace(pos, len, newStr) modifies s in place
  • If newStr is longer than len, the string grows automatically
  • Pair with find(): s.replace(s.find("old"), 3, "new")

replace()

C++

Find the word to replace, then use replace() at that position.

insert()

insert(pos, str) inserts str into the string at index pos, shifting existing characters to the right.

insert()

insert(0, str) prepends to the string; insert(s.size(), str) is equivalent to append().

  • s.insert(pos, str) inserts str before the character at pos
  • s.insert(pos, n, ch) inserts ch repeated n times at pos
  • All characters from pos onward shift right

insert()

C++

Insert a comma in the middle and prepend a prefix.

erase()

erase(pos, len) removes len characters starting at pos. If len is omitted, it erases from pos to the end.

erase()

erase() modifies the string in place and returns a reference to it, the original string is changed.

  • s.erase(pos) removes everything from pos to end
  • s.erase(pos, len) removes exactly len characters
  • s.erase() with no arguments clears the entire string (same as s.clear())
  • Combine with find() to remove the first occurrence of a substring

erase()

C++

Remove a slice from the middle, then remove everything from a position onward.

c_str()

c_str() returns a const char* pointer to the null-terminated C-style version of the string. Use it when calling C library functions or APIs that expect a char* argument.

c_str()

The pointer returned by c_str() is only valid as long as the string is not modified, never store it past a string modification.

  • Returns const char*, the underlying buffer of the std::string
  • Automatically null-terminated
  • Use when interacting with C APIs (fopen, printf, legacy functions)
  • The pointer is invalidated if the string is resized or modified

c_str()

C++

Get the const char* pointer to pass the string to a C function like strlen.

std::string Methods at a Glance

MethodPurposeReturns
s.length() / s.size()Number of characterssize_t
s.empty()True if string has no charactersbool
s.append(str)Append str to endstring&
s.substr(pos, len)Extract substringstring (new)
s.find(str)Index of first match, or npossize_t
s.rfind(str)Index of last match, or npossize_t
s.replace(pos, len, str)Replace len chars at pos with strstring&
s.insert(pos, str)Insert str before posstring&
s.erase(pos, len)Remove len chars at posstring&
s.clear()Remove all charactersvoid
s.c_str()const char* pointer to null-terminated dataconst char*

Knowledge Check

1. Which header is required to use std::string?

2. What does s.length() return?

3. What does s.find("lo") return if "lo" is not found?

4. Which method extracts a portion of a string?

5. What does s.c_str() return?

6. How do you compare two std::strings for equality?

7. Which method appends one string to another?