Question

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?

Was it helpful?

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.

OTHER TIPS

A boost-less solution is:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    const std::string example("eXamPLe");

    std::string s = example;    
    s[0] = toupper(s[0]);
    std::transform(s.begin()+1, s.end(), s.begin()+1, tolower);
    
    std::cout << s << "\n";
}

I think the string variable name is example and the string stored in it is "example". So try this:

example[0] = toupper(example[0]);
for(int i=1 ; example[i] != '\0' ; ++i){
        example[i] = tolower(example[i]);
        }

cout << example << endl;

This might give you the first character CAPITALIZED and the rest of the string becomes lowercase. It's not quite different from the original solution but just a different approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top