Lesson content
Read, practise, then check your understanding
A C-style string is a character array ending with \0. Functions such as strlen depend on that terminator and cannot know the buffer capacity. std::string owns dynamic character storage and supplies safe size-aware construction, concatenation, search, replacement, and comparison.
#include <iostream>
#include <string>
#include <string_view>
std::string normalize(std::string_view first, std::string_view last) {
std::string result{first};
result += ' ';
result.append(last);
return result;
}
std::string line;
std::getline(std::cin, line);
operator>> stops at whitespace; std::getline reads a full line. If you mix them, consume the pending newline deliberately, often with std::ws.
Views, parsing, and compatibility
std::string_view is a cheap non-owning pointer-and-length view. It is excellent for read-only parameters but can dangle if the source string is destroyed or reallocated. It is not guaranteed to be null-terminated. Use string.c_str() for a temporary bridge to an API expecting const char*; modifications may invalidate the pointer.
find returns std::string::npos when absent. substr creates a string, while a view’s substr remains non-owning. std::stoi and relatives parse with exceptions; std::from_chars offers allocation-free, error-code parsing. A std::string counts code units, not user-perceived Unicode characters, so international text may require a dedicated Unicode library.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.