问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/15369910/how-to-capitalize-a-word-in-a-c-string