C++ Strings
C++ strings are handled by the std::string class from <string>. Unlike C character arrays, std::string manages its own memory, grows automatically and supports operators like + and ==.
Creating and Joining Strings
#include <iostream>
#include <string>
int main() {
std::string first = "Naeem";
std::string last = "Amin";
std::string full = first + " " + last;
full += "!";
std::cout << full << " has " << full.size() << " characters\n";
}Naeem Amin! has 11 characters
Accessing Characters
Use [] for fast access or .at() for bounds-checked access that throws an exception if the index is invalid.
#include <iostream>
#include <string>
int main() {
std::string word = "Code";
word[0] = 'M';
std::cout << word << ' ' << word.at(3) << ' ' << word.back() << '\n';
}Mode e e
Useful std::string Methods
#include <iostream>
#include <string>
int main() {
std::string s = "learn modern c++";
std::cout << s.substr(6, 6) << '\n'; // from index 6, 6 chars
std::cout << s.find("c++") << '\n'; // position
s.replace(0, 5, "master");
std::cout << s << '\n';
std::cout << std::boolalpha << s.starts_with("master") << '\n'; // C++20
}modern 13 master modern c++ true
Numbers and Strings
std::to_string turns a number into text, and std::stoi / std::stod parse text into numbers.
#include <iostream>
#include <string>
int main() {
int n = std::stoi("41") + 1;
std::string msg = "Answer: " + std::to_string(n);
std::cout << msg << '\n';
}Answer: 42
Comparing Strings
With std::string you can compare using ==, !=, < and >, which compare the text alphabetically. This is much simpler than C's strcmp.
Frequently asked questions
What is the difference between size() and length() for std::string?
There is no difference; both return the number of characters. size() is consistent with other containers.
How do I convert an int to a string in C++?
Use std::to_string(number), or std::format("{}", number) in C++20.
What does find return if the text is not found?
It returns std::string::npos, a special very large value. Always compare the result with npos before using it.