C++ Strings
std::string, from the string header, holds text. Unlike C strings, it grows as needed, knows its length, and can be joined with + and compared with ==.
Creating and joining
#include <iostream>
#include <string>
int main() {
std::string first = "Asha";
std::string last = "Kumar";
std::string full = first + " " + last;
full += "!";
std::cout << full << "\n";
std::cout << "Length: " << full.length() << "\n";
return 0;
}Asha Kumar! Length: 11
length() and size() are the same. At least one side of a + must be a std::string: "a" + "b" with two quoted texts does not compile.
Characters
Square brackets give one character, counting from 0; front() and back() give the first and last. at(i) does the same as [i] but throws an exception when the index is outside the string.
#include <iostream>
#include <string>
int main() {
std::string word = "programming";
std::cout << word[0] << " " << word.back() << "\n";
word[0] = 'P';
std::cout << word << "\n";
int vowels = 0;
for (char c : word) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') vowels++;
}
std::cout << vowels << " vowels\n";
return 0;
}p g Programming 3 vowels
Searching and cutting
find returns the position of a piece of text, or std::string::npos when it is not there. substr(start, count) returns a part. replace and insert change the string.
#include <iostream>
#include <string>
int main() {
std::string s = "I like C and C++";
std::cout << s.find("C") << "\n";
std::cout << s.substr(7, 1) << "\n";
if (s.find("Java") == std::string::npos) std::cout << "no Java\n";
s.replace(2, 4, "love");
std::cout << s << "\n";
return 0;
}7 C no Java I love C and C++
Comparing and converting
==, != and < compare strings by their characters (alphabetical order for letters of the same case). std::to_string(42) turns a number into a string; std::stoi and std::stod turn a string into an int or a double, and throw an exception if it is not a number.
#include <iostream>
#include <string>
int main() {
std::string a = "apple", b = "banana";
std::cout << std::boolalpha << (a < b) << " " << (a == "apple") << "\n";
int n = std::stoi("42");
std::string text = "Total: " + std::to_string(n * 2);
std::cout << text << "\n";
return 0;
}true true Total: 84
std::string or C strings?
C++ still understands C strings (arrays of char ending with '\0'), and text in quotes is such an array. But std::string manages its own memory, so it cannot overflow, and it offers all the operations above. Use std::string in C++ code. When an old C function needs a C string, s.c_str() gives one.
Strings are passed to functions as const std::string& (a reference, see References) so the text is not copied; C++17's std::string_view is an even lighter way to pass text you only read.
Practice exercises
- Read a word and print whether it is a palindrome.
- Count the words in a line read with
getline. - Replace every space in a sentence with
-. - Change a word to upper case with
toupperfromcctypein a loop.