Lesson 5 of 12

Characters become strings

Separate characters from numbers, then safely inspect and edit managed text.

A character is not its numeric meaning

char digitCharacter = '7', int digitValue = 7, and std::string text = "7" have different types. Single quotes name one character; double quotes describe text. '\n' is one newline character despite its two-character source spelling.

For a character known to be a digit, c − '0' produces its numeric value. First check '0' <= c && c <= '9' when input is not guaranteed numeric. Subtracting integer zero would leave the character code instead.

A managed sequence with a length

Include <string> to use std::string. It manages its own storage and can change length. std::string s starts empty; std::string spaces(3, ' ') starts with three spaces. size() and length() count stored char elements, and empty() asks whether that count is zero.

For existing content, use indices from 0 to length − 1. Replacing s[0] changes a character but does not grow the string. Unlike raw arrays, strings support whole-value copying, assignment, and content comparison.

C++23
#include <iostream>
#include <string>

int main() {
    std::string word = "code";
    std::cout << word.size() << ' ' << word[0] << '\n';
    word[0] = 'm';
    word.push_back('s');
    std::cout << word << '\n';
    word.pop_back();
    std::cout << word << '\n';
    word.clear();
    std::cout << std::boolalpha << word.empty() << '\n';
    return 0;
}

Appending and empty-string boundaries

push_back(c) appends a character. pop_back() removes the last one. front(), back(), and pop_back() require a nonempty string. clear() removes all content; printing an empty string or appending to it is valid.

Do not append by assigning s[s.size()]. C++23 gives that position a special null-terminator rule; it is not an ordinary content cell or a spare slot for a non-null character. Use push_back instead.

Character and index assumptions

The source exercises use ASCII text. Letter checks such as 'a' <= c && c <= 'z' suit that setting; they are not a general Unicode method. Uppercase and lowercase characters differ.

String size uses an unsigned type. Under the training bound of at most 100000 characters, converting size() to a 32-bit-or-wider int is safe. Convert before subtracting one: s.size() − 1 wraps for an empty string, whereas an int n followed by n − 1 produces −1.

String studio

ASCII characters match the one-byte C++ examples. Spaces and letter case count.

l0
e1
v2
e3
l4
Length5
Reversedlevel

✓ This is a palindrome: it reads the same in both directions.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

Starting with s = "hi", apply s[0] = 'b' and s.push_back('!'). What is s?

Choose an answer
Try it yourself

Turn the idea into code

Read one non-whitespace ASCII character. If it is a digit, print its numeric value and twice that value. Otherwise print NOT A DIGIT.

Give me a hint

Check the digit range before subtracting '0'.

Show the explained solution

The range check proves the conversion represents a decimal digit. Input 7 gives 7 14; input A gives NOT A DIGIT.

C++23
#include <iostream>

int main() {
    char c = ' ';
    std::cin >> c;
    if ('0' <= c && c <= '9') {
        int digit = c - '0';
        std::cout << digit << ' ' << digit * 2 << '\n';
    } else {
        std::cout << "NOT A DIGIT\n";
    }
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.