4.4 std::string
C++ programs usually use std::string for text. A std::string object knows its own length, can grow when you append text, and has useful methods for searching, slicing, and editing.
#include <iostream>
#include <string>
int main() {
std::string name = "Ada";
std::cout << "Hello, " << name << std::endl;
return 0;
}Use size() or length() to get the number of characters. They mean the same thing for std::string.
std::string word = "program";
std::cout << word.size() << std::endl; // 7
std::cout << word.length() << std::endl; // 7Use indexes when you need one character.
std::cout << word[0] << std::endl; // p
std::cout << word[word.size() - 1] << std::endl; // mThe first index is 0, just like arrays. front() returns the first character, and back() returns the last character.
std::cout << word.front() << std::endl;
std::cout << word.back() << std::endl;Strings can be combined with + or +=.
std::string first = "Grace";
std::string last = "Hopper";
std::string full = first + " " + last;
full += "!";Strings can be compared with ==, !=, <, and >. The ordering is lexicographic, which means dictionary-like order based on character codes.
if (password == "leaflet") {
std::cout << "ok" << std::endl;
}
if ("apple" < "banana") {
std::cout << "apple comes first" << std::endl;
}Use find() to search for a character or substring. It returns the first position, or std::string::npos if the text is not found.
std::string email = "[email protected]";
std::size_t at = email.find('@');
if (at != std::string::npos) {
std::cout << "The @ is at index " << at << std::endl;
}rfind() searches from the right, which is useful when you need the last occurrence.
std::size_t dot = email.rfind('.');Use substr(start, count) to copy part of a string.
std::string domain = email.substr(at + 1); // example.com
std::string user = email.substr(0, at); // studentUse insert(), erase(), and replace() when you need to edit the text.
std::string label = "C++";
label.insert(0, "Learn ");
label.replace(0, 5, "Practice");
label.erase(label.size() - 3);Use std::getline() when you need a whole line that may contain spaces. If you previously read with std::cin >>, you may need to consume the leftover newline before calling std::getline().
std::string sentence;
std::getline(std::cin, sentence);A range-based for loop is a clean way to visit every character.
for (char ch : sentence) {
std::cout << ch << std::endl;
}