TITLECASE - Editorial

Prerequisites:- None

Problem :- Convert a given string into title case, where the first letter of each word is capitalized and the rest are in lowercase, except for words entirely in uppercase (acronyms), which remain unchanged.

Explanation :-
Split the input string into individual words based on spaces.
For each word:
Check if it is entirely in uppercase. If yes, it’s an acronym, so keep it unchanged.
If not, capitalize the first letter and convert the rest of the letters to lowercase.
Join all the modified words back together into a single string with spaces between them.
Output the resulting title case string.

Solution :-
C++ Solution : -

#include <iostream>
#include <sstream>
#include <cctype>
using namespace std;

// Function to convert a word to title case
string convertToTitleCase(const string& word) {
    string result = "";
    for (int i = 0; i < word.length(); i++) {
        if (i == 0)
            result += toupper(word[i]);  // Capitalize the first letter
        else
            result += tolower(word[i]);  // Convert the rest to lowercase
    }
    return result;
}

int main() {
    int T;
    cin >> T;
    cin.ignore();  // Consume the newline character after reading T

    for (int t = 0; t < T; t++) {
        string S;
        getline(cin, S);

        istringstream iss(S);
        string word;
        bool firstWord = true;

        while (iss >> word) {
            if (!firstWord) {
                cout << " ";
            }
            firstWord = false;

            // Check if the word is an acronym (entirely in uppercase)
            bool isAcronym = true;
            for (char c : word) {
                if (!isupper(c)) {
                    isAcronym = false;
                    break;
                }
            }

            if (isAcronym) {
                cout << word;  // If it's an acronym, print as is
            } else {
                cout << convertToTitleCase(word);  // Convert to title case
            }
        }

        cout << endl;
    }

    return 0;
}