C++ practice

C++ String Exercises with Solutions for Beginners

These eight short programs practice common operations with std::string. Each solution is a complete C++17 program with a visible result. Read the task first, predict the output, then open its solution. The examples also make boundary behavior explicit: an empty string is valid input, a missing search result is represented by std::string::npos, and a search for an empty target succeeds at position zero.

Choose safe string operations

A string can have length zero. Before reading its first character, check whether it is empty or use an operation whose behavior covers that case. Reversing an empty string is safe, and its result remains empty. An index-based loop should compare its index with text.size() before accessing the character at that index.

Search functions return std::string::size_type. A failed find call returns the special value std::string::npos, not a valid position. Compare against that named value before using the result as an index. Searching for an empty target is defined: find("") returns zero, including when the source string is empty.

Character classification and conversion functions in <cctype> accept EOF or a value representable as unsigned char. A plain char can be negative on some implementations. Convert each character with static_cast<unsigned char> before passing it to std::tolower, std::toupper, or std::isspace. This cast avoids undefined behavior for negative char values.

The programs below use literal input so you can compile and compare their output without an interactive prompt. Each task describes a small variation you can make after the verified solution runs. Treat the sample as a starting point: try an empty value, a one-character value, and a value with the feature at the beginning or end. These checks reveal off-by-one mistakes quickly.

Common mistakes

Do not read text[0] unless the string contains a character. An empty string has size zero, so index zero is outside its valid range. Use a loop condition that checks the size before access, or use an operation such as find whose result you validate.

Do not treat std::string::npos as the end position. It is a sentinel value that means no match exists. Check it before subtracting positions, taking a substring, or indexing. A search for an empty target is a different case: it returns zero, so it is found at the beginning.

Do not pass a possibly negative plain char directly to <cctype>. Cast to unsigned char for every call to std::tolower, std::toupper, and std::isspace. Finally, decide whether your task means ASCII spaces or all locale whitespace. The trim example removes only the ordinary space character; a whitespace-aware version can use std::isspace with the same cast.

Exercise

Complete these eight independent tasks. Each solution is hidden so you can work through the string operation first, then compare your approach with a C++17 program.

1. Count vowels

Count the vowels in a word without treating uppercase and lowercase letters differently. Try changing the text to an empty string; the count should be zero.

Show solution
#include <cctype>
#include <iostream>
#include <string>

int main() {
    const std::string text = "Education";
    int count = 0;
    for (char ch : text) {
        const char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
        if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
            ++count;
        }
    }
    std::cout << count << '\n';
    return 0;
}

Output:

5

2. Reverse a string

Build a reversed copy by reading the original characters from the last position to the first. An empty source skips the loop and produces an empty result.

Show solution
#include <iostream>
#include <string>

int main() {
    const std::string text = "loops";
    std::string reversed;
    for (std::string::size_type i = text.size(); i > 0; --i) {
        reversed += text[i - 1];
    }
    std::cout << reversed << '\n';
    return 0;
}

Output:

spool

3. Check a palindrome

Compare a string with its reversed copy. This version treats letter case and spaces as significant. An empty string compares equal to its empty reverse.

Show solution
#include <iostream>
#include <string>

int main() {
    const std::string text = "level";
    std::string reversed(text.rbegin(), text.rend());
    std::cout << std::boolalpha << (text == reversed) << '\n';
    return 0;
}

Output:

true

4. Trim surrounding spaces

Find the first and last non-space character, then take that inclusive range. If every character is a space, return an empty string instead of creating a range from invalid positions.

Show solution
#include <iostream>
#include <string>

int main() {
    const std::string text = "   clean text   ";
    const auto first = text.find_first_not_of(' ');
    std::string trimmed;
    if (first != std::string::npos) {
        const auto last = text.find_last_not_of(' ');
        trimmed = text.substr(first, last - first + 1);
    }
    std::cout << '[' << trimmed << "]\n";
    return 0;
}

Output:

[clean text]

5. Count words

Read whitespace-delimited words from a string stream. No tokens means the count stays zero, so an empty sentence needs no special index handling.

Show solution
#include <iostream>
#include <sstream>
#include <string>

int main() {
    const std::string text = "practice one step at a time";
    std::istringstream input(text);
    std::string word;
    int count = 0;
    while (input >> word) {
        ++count;
    }
    std::cout << count << '\n';
    return 0;
}

Output:

6

6. Replace a character

Replace every lowercase a with o. If no character matches, the original string remains unchanged. The loop also handles an empty string by doing zero iterations.

Show solution
#include <iostream>
#include <string>

int main() {
    std::string text = "banana";
    for (char& ch : text) {
        if (ch == 'a') {
            ch = 'o';
        }
    }
    std::cout << text << '\n';
    return 0;
}

Output:

bonono

7. Find a substring

Print the position of a target or a message when the result equals npos. Also search for an empty string and print that position. text.find("") returns 0 because an empty string matches at the start.

Show solution
#include <iostream>
#include <string>

int main() {
    const std::string text = "banana";
    const std::string target = "nan";
    const auto position = text.find(target);
    const auto emptyTargetPosition = text.find("");
    if (position == std::string::npos) {
        std::cout << "not found\n";
    } else {
        std::cout << position << '\n';
    }
    std::cout << emptyTargetPosition << '\n';
    return 0;
}

Output:

2
0

8. Capitalize each word

Uppercase the first non-space character after each run of spaces. The cast protects the std::toupper argument, and an empty string simply prints an empty line.

Show solution
#include <cctype>
#include <iostream>
#include <string>

int main() {
    std::string text = "small steps matter";
    bool atWordStart = true;
    for (char& ch : text) {
        if (std::isspace(static_cast<unsigned char>(ch))) {
            atWordStart = true;
        } else if (atWordStart) {
            ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
            atWordStart = false;
        }
    }
    std::cout << text << '\n';
    return 0;
}

Output:

Small Steps Matter

Keep learning with CppPath

Continue with std::string Basics, std::string Operations, and Character Classification and Conversion. Each full lesson includes a quiz and a checked coding challenge with a free account.