LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 6

Capitalize the first letter of every word in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Convert a sentence to title case: the first letter of each word uppercase and the remaining letters lowercase.

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

int main() {
    std::string s = "the qUICK brown fox jumps over THE lazy dog";
    bool new_word = true;
    for (char& c : s) {
        unsigned char u = static_cast<unsigned char>(c);
        if (std::isalpha(u)) {
            c = static_cast<char>(new_word ? std::toupper(u) : std::tolower(u));
            new_word = false;
        } else {
            new_word = true;
        }
    }
    std::cout << s << '\n';
    return 0;
}

Output Verified by compiling and running

The Quick Brown Fox Jumps Over The Lazy Dog

A flag remembers whether the previous character ended a word. The reference loop changes the string in place.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links