How to convert a string to title case in C++

3 Answers

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

void toTitleCase(std::string& s) {
    bool newWord = true;

    for (char& c : s) {
        if (std::isspace(static_cast<unsigned char>(c))) {
            newWord = true;
        } else {
            if (newWord) {
                c = std::toupper(static_cast<unsigned char>(c));
                newWord = false;
            } else {
                c = std::tolower(static_cast<unsigned char>(c));
            }
        }
    }
}

int main() {
    std::string s = "hELLo woRLD from c++";
    
    toTitleCase(s);
    
    std::cout << s << "\n";
}


/*
run:

Hello World From C++

*/

 



answered 9 hours ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>

void toTitleCase(std::string& s) {
    bool newWord = true;

    for (char& c : s) {
        if (std::isspace(static_cast<unsigned char>(c))) {
            newWord = true;
        } else {
            if (newWord) {
                c = std::toupper(static_cast<unsigned char>(c));
                newWord = false;
            } else {
                c = std::tolower(static_cast<unsigned char>(c));
            }
        }
    }
}

std::string toTitleCaseCopy(const std::string& s) {
    std::string result = s;
    toTitleCase(result);
    
    return result;
}

int main() {
    std::string s = "hELLo woRLD from c++";
    
    std::cout << toTitleCaseCopy(s) << "\n";
}



/*
run:

Hello World From C++

*/

 



answered 9 hours ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype> // toupper // tolower
#include <algorithm>

std::string toTitleCase(std::string s) {
    bool newWord = true;

    std::transform(s.begin(), s.end(), s.begin(),
        [&](char c) {
            unsigned char uc = static_cast<unsigned char>(c);

            if (std::isspace(uc)) {
                newWord = true;
                return c; // still char
            }
            if (newWord) {
                newWord = false;
                return static_cast<char>(std::toupper(uc));
            }
            return static_cast<char>(std::tolower(uc));
        });

    return s;
}

int main() {
    std::string s = "hELLo woRLD from c++";
    
    std::cout << toTitleCase(s) << "\n";
}



/*
run:

Hello World From C++

*/

 



answered 8 hours ago by avibootz
...