Wednesday, July 20, 2011

C++ capitalize each word in string

(Go here for C# implementation)

So here it is: source code for capitalizing first letter of each word in string
#include <iostream>
#include <string>
#include <algorithm>
#include <locale>

using std::string;
using std::locale;
using std::endl;
using std::cout;

int main()
{
    locale loc;

    string text = "How to capitalize the first character of each word?"
        " Other characters should be lower case.";

    cout << text << endl;

    int count = text.size();
    if (count > 0)   
    {
        text[0] = toupper(text[0], loc);
    }

    for(int i = 1; i < count; i++)
    {
        if (isspace(text[i - 1], loc))
            text[i] = toupper(text[i], loc);
        else
            text[i] = tolower(text[i]);
    }

    cout << text << endl;

    return 0;
}