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

送分小仙女□ 提交于 2019-12-13 16:44:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!