Search code examples
c++booststdstringcapitalize

How to capitalize a word in a C++ string?


I have a std::string and wish for the first letter to be capitalized and the rest lower case.

One way I could do this is:

const std::string example("eXamPLe");
std::string capitalized = boost::to_lower_copy(example);

capitalized[0] = toupper(capitalized[0]);

Which would yield capitalized as:

"Example"

But perhaps there is a more straight forward way to do this?


Solution

  • If the string is indeed just a single word, std::string capitalized = boost::locale::to_title (example) should do it. Otherwise, what you've got is pretty compact.

    Edit: just noticed that the boost::python namespace has a str class with a capitalize() method which sounds like it would work for multi word strings (assuming you want what you described and not title case). Using a python string just to gain that functionality is probably a bad idea, however.