Question 6
Back to Exercise
Convert a sentence to title case: the first letter of each word uppercase and the remaining letters lowercase.
Solution
#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;
}
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!