Lesson 7 of 12

Scan text: count, filter, transform

Build a result from matching characters without losing leading zeros or skipping shifted text.

One character, one decision

String traversal is an array scan whose elements are characters. A local char c = s[i] is a copy: assigning to c does not update s[i]. Write to the actual indexed character when you intend a change.

To count vowels, write a complete equality for each accepted letter and join them with ||. c == 'a' || 'e' is wrong because the second operand is a nonzero character value, not another comparison. Decide whether uppercase counts from the task.

Build filtered output separately

Filtering retains only characters satisfying a rule, in their original order. Begin with an empty result and append accepted characters. Removing characters while moving forward through the same string can shift the next character into an index you have already passed.

This example reads one ASCII line of at most 100000 characters. It retains digit characters and independently sums their numeric values. For room 20B, floor 3, it produces 203 and 5.

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

int main() {
    std::string s;
    std::getline(std::cin, s);
    std::string digits;
    int sum = 0;
    int n = static_cast<int>(s.size());
    for (int i = 0; i < n; ++i) {
        if ('0' <= s[i] && s[i] <= '9') {
            digits.push_back(s[i]);
            sum += s[i] - '0';
        }
    }
    std::cout << digits << '\n' << sum << '\n';
    return 0;
}

A huge number can remain text

A 100000-digit integer cannot fit a built-in integer type, but its digit sum still needs only a scan. Its maximum possible digit sum is 9 × 100000 = 900000, which fits the training environment’s int.

Keeping a string preserves leading zeros: a09b2 filters to 092, with sum 11. Converting the whole result to an integer would change its representation. Other tasks can set flags for uppercase, lowercase, and digit categories, then combine those flags with a minimum-length condition.

Pause & predict

The digit filter receives a09b2. What text and digit sum does it produce?

Choose an answer
Try it yourself

Turn the idea into code

Read one lowercase ASCII word of length at most 100000. Remove the vowels a, e, i, o, u and print the remaining characters in order.

Give me a hint

Use a fresh result string. Append only when the complete vowel condition is false.

Show the explained solution

The source word remains unchanged during traversal, so no indices shift. A word containing only vowels produces an empty output line.

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

int main() {
    std::string s;
    std::cin >> s;
    std::string result;
    int n = static_cast<int>(s.size());
    for (int i = 0; i < n; ++i) {
        char c = s[i];
        bool vowel = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
        if (!vowel) { result.push_back(c); }
    }
    std::cout << result << '\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.