← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 8 of 15

C++ STL String

The STL string is C++'s easy-to-use text type, with many built-in tools for changing and searching text. It handles the memory for you.
Syntax
cpp
std::string string_name = "text";
string_name.append("more");
string_name.insert(position, "text");
string_name.erase(position, count);

String Creation and Basic Methods

std::string is a safe, dynamically-resizing container for text that manages its own memory automatically, unlike a raw char array which has a fixed size and no bounds checking.

You create one from a literal, another string, or repeated characters, and the class handles allocation behind the scenes.

Example: String Creation and Basic Methods

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Program execution starts in main()
int main() {
	std::string name = "Alex";
	// Print to the console with cout
	std::cout << name.length() << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

String Modification

Methods like append(), insert(), erase(), and operator+= let you grow or shrink a string's contents without manually managing buffer size.

Because std::string resizes itself, these operations are far safer than writing past the end of a fixed-size C-style char array.

Example: String Modification

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Program execution starts in main()
int main() {
	std::string text = "Hello";
	text.append(" World");
	text += "!";
	// Print to the console with cout
	std::cout << text << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Finding Substrings

find() scans for a character or substring and returns the zero-based index of the first match, or the special value std::string::npos if nothing is found -- always check against npos rather than assuming a valid index. rfind() performs the same search from the end.

Example: Finding Substrings

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Program execution starts in main()
int main() {
	std::string text = "Hello, World!";
	// Declare pos and set it to text.find("World")
	size_t pos = text.find("World");
	if (pos != std::string::npos) std::cout << "Found at " << pos << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Substrings and Comparisons

substr(pos, len) extracts a new string starting at a given position, which is handy for parsing fixed-format text like dates or filenames.

Comparison operators (==, <, >) compare strings lexicographically, character by character, the same way words sort in a dictionary.

Example: Substrings and Comparisons

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Program execution starts in main()
int main() {
	std::string date = "2024-01-15";
	std::string year = date.substr(0, 4);
	// Print to the console with cout
	std::cout << year << std::endl;
	// Print to the console with cout
	std::cout << (year == "2024") << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Numeric Conversions

std::stoi, std::stod, and similar functions convert a string holding digits into an int or double, throwing std::invalid_argument if the text isn't a valid number. std::to_string does the reverse, turning a number into its string representation for display or concatenation.

Example: Numeric Conversions

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Program execution starts in main()
int main() {
	std::string input = "42";
	// Declare number and set it to std::stoi(input)
	int number = std::stoi(input);
	std::string back = std::to_string(number * 2);
	// Print to the console with cout
	std::cout << back << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Confusing std::string with C-style char* strings.
  2. Passing a start index bigger than the length to substr, which throws std::out_of_range.
  3. Comparing the result of find with -1 instead of std::string::npos.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.