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

C++ STL String

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 <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	std::cout << name.length() << std::endl;
	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 <iostream>
#include <string>

int main() {
	std::string text = "Hello";
	text.append(" World");
	text += "!";
	std::cout << text << std::endl;
	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 <iostream>
#include <string>

int main() {
	std::string text = "Hello, World!";
	size_t pos = text.find("World");
	if (pos != std::string::npos) std::cout << "Found at " << pos << std::endl;
	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 <iostream>
#include <string>

int main() {
	std::string date = "2024-01-15";
	std::string year = date.substr(0, 4);
	std::cout << year << std::endl;
	std::cout << (year == "2024") << std::endl;
	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 <iostream>
#include <string>

int main() {
	std::string input = "42";
	int number = std::stoi(input);
	std::string back = std::to_string(number * 2);
	std::cout << back << std::endl;
	return 0;
}

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.