CodeBlanks Logo Icon CodeBlanks

String helpers

Add and test string processing functions.

String helpers

In this lesson we add the first helper method to the Helpers class: capitalize. This method uppercases the first letter of a string. In C++ the std::toupper function uppercases a single character.

Example: static std::string capitalize(std::string text) { if (text.empty()) return text; text[0] = std::toupper(text[0]); return text; }. Here text.empty() checks for an empty string; text[0] accesses the first character. Call: Helpers::capitalize("hello") returns "Hello". We take the previous lesson's skeleton and add this method.

Calling the method

A static method is called with the class name and two colons (::). No instance is needed: Helpers::capitalize("hello"). You can print the returned value with std::cout.

To see output on separate lines, use std::endl: std::cout << Helpers::capitalize("hello") << std::endl;. This prints Hello and moves to the next line. After the previous lesson's "Ready" output, Hello appears on a new line. This way the output of two lessons accumulates.

Practice Add the capitalize method and call it

Take the previous lesson's Helpers skeleton. Under public: add static std::string capitalize(std::string text) with body if (text.empty()) return text; text[0] = std::toupper(text[0]); return text;. In main after std::cout << "Ready" << std::endl; add std::cout << Helpers::capitalize("hello");.

Starter code

main.cpp
#include <iostream>
#include <string>

class Helpers {
};

int main() {
    std::cout << "Ready";
    // Add the capitalize method and call it
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
#include <cctype>

class Helpers {
public:
    static std::string capitalize(std::string text) {
        if (text.empty()) return text;
        text[0] = std::toupper(text[0]);
        return text;
    }
};

int main() {
    std::cout << "Ready" << std::endl;
    std::cout << Helpers::capitalize("hello");
    return 0;
}

Expected output

Ready
Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does capitalize("hello") return?

main.cpp
Helpers::capitalize("hello")
  • "HELLO"
  • "Hello" Correct answer
  • "hello"
  • "hELLO"

Explanation: Only the first letter is uppercased: Hello.

2 Uppercase the first letter

Question
text[0] = std::____(text[0]);
Answer
text[0] = std::toupper(text[0]);

Explanation: std::toupper uppercases a single character.

3 Match each piece to its role

Term Meaning
static Enables call without instance
std::toupper Uppercases a character
text.empty() Empty string check
Helpers::capitalize Method call

All lessons in Intermediate