Skip to content

Chapter 9 of 31

Strings and String Handling

Compare C strings, std::string, string_view, parsing, searching, and lifetime rules.

36 minutes 10 quick checksBy Subha Prasad
Lesson 9 of 31Course navigation

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.

Which type owns a resizable text sequence?
What terminates a C-style string?
Which non-owning C++17 type views string data?
How does std::getline differ from operator >> for string input?
What must outlive a std::string_view?
What does std::string::size report?
What does c_str() return?
What may invalidate pointers into a string?
Which function converts text to int with exception reporting?
Why is string_view efficient as a read-only parameter?

0 of 10 checks passed

Your progress is saved on this device.