C++ STL String
In this page:
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
#include <iostream>
#include <string>
int main() {
std::string name = "Alex";
std::cout << name.length() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
text.append(" World");
text += "!";
std::cout << text << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: