Lesson 12 of 12

Optional: subsequences and useful tools

Distinguish consecutive pieces from ordered selections, then recognize safer library conveniences.

Consecutive is different from in-order

A subarray and a substring are consecutive pieces. A subsequence may skip values, but must preserve their original order. In abcde, bcd is a substring; ace is a subsequence but not a substring; ca is not a subsequence.

A prefix begins at the start and a suffix reaches the end. To check a subsequence, scan the text with one index and keep another count of pattern characters already matched. Match the earliest available character, leaving as much remaining text as possible for later matches.

An empty pattern is a subsequence of any text. A nonempty pattern is not a subsequence of empty text. Guard matched < needed before reading pattern[matched], including after the entire pattern has matched.

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

int main() {
    std::string pattern, text;
    std::getline(std::cin, pattern);
    std::getline(std::cin, text);
    int needed = static_cast<int>(pattern.size());
    int n = static_cast<int>(text.size());
    int matched = 0;
    for (int i = 0; i < n; ++i) {
        if (matched < needed && text[i] == pattern[matched]) {
            ++matched;
        }
    }
    std::cout << (matched == needed ? "YES" : "NO") << '\n';
    return 0;
}

Fixed containers and range-based loops

std::array<int, 4> from <array> is a fixed-size standard-library wrapper supporting size(), copying, and content comparison. Its size is still a compile-time choice. A partly used std::array<int, 1000> still reports size 1000, so shorter inputs need an active length.

for (char c : s) visits copies of the characters. for (char& c : s) provides writable references to the stored characters. A range loop over a raw array visits its entire capacity, not just your active n; keep index loops when the active range is shorter.

Edit pieces and ask text questions

String insert(pos, text), erase(pos, count), and replace(pos, count, text) modify the current string. A starting position beyond size() is out of range. After changes, old lengths and saved indices may no longer identify the same characters.

starts_with and ends_with ask about a beginning or ending; contains asks about occurrence anywhere. The first two are available since C++20 and contains since C++23. They return a Boolean, unlike find, which returns a position or npos.

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

int main() {
    std::string s = "team";
    s.insert(0, "HNU ");
    std::cout << s << '\n';
    s.erase(0, 4);
    s.replace(0, 4, "ICPC");
    std::cout << s << '\n';
    std::cout << std::boolalpha << s.starts_with("IC") << '\n';
    std::cout << s.ends_with("PC") << '\n';
    std::cout << s.contains("CP") << '\n';
    return 0;
}

Character tools and terminators

<cctype> offers isdigit, isalpha, isspace, tolower, and toupper. When passing a possibly signed char, convert it to unsigned char first. For example, static_cast<char>(std::tolower(static_cast<unsigned char>(s[i]))) safely stores the conversion result. These functions may depend on the active C locale and are not a complete Unicode solution.

A C-style string needs a terminating null character: char text[4] = "HNU" stores H, N, U, and '\0'. char letters[3] = {'H', 'N', 'U'} has no terminator and must not be passed to operations expecting one. std::string tracks its length, so prefer it for this training.

These optional tools are for recognition after the core scans make sense. Explain the bounds, initial state, and result of an ordinary loop before replacing it with a shorter spelling.

Pause & predict

For text abc, which statement is correct?

Choose an answer
Try it yourself

Turn the idea into code

Optional: read a full ASCII line and replace every hyphen with a plus sign using a range-based loop. Explain why char c alone would not modify the string.

Give me a hint

Use a writable reference to each stored character.

Show the explained solution

char& c aliases the current character. Assigning through it changes the string; a plain char c would be only a copy.

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

int main() {
    std::string s;
    std::getline(std::cin, s);
    for (char& c : s) {
        if (c == '-') { c = '+'; }
    }
    std::cout << s << '\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.