How to check if a string is title case in C++

1 Answer

0 votes
#include <iostream>
#include <cctype>
#include <string>

bool isTitleCase(const std::string& s) {
    bool newWord = true;

    for (unsigned char c : s) {
        if (std::isspace(c)) {
            newWord = true;
        } else {
            if (newWord) {
                if (!std::isupper(c)) return false;
                newWord = false;
            } else {
                if (!std::islower(c)) return false;
            }
        }
    }

    return true;
}

int main() {
    std::cout << std::boolalpha;
    
    std::cout << isTitleCase("Hello World") << "\n";   // true
    std::cout << isTitleCase("Hello world") << "\n";   // false
    std::cout << isTitleCase("hello World") << "\n";   // false
}



/*
run:

true
false
false

*/

 



answered 7 hours ago by avibootz
edited 7 hours ago by avibootz
...