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?
Today we will learn how to code a C program on how to Capitalize first and last letter of each word of a string i.e. to convert first and last letter of each word into uppercase . We will use toupper() function in the process. The toupper() function is used to convert lowercase alphabet to uppercase.
toupper() function in C The toupper() function is used to convert lowercase alphabet to uppercase. i.e. If the character passed is a lowercase alphabet then the toupper() function converts a lowercase alphabet to an uppercase alphabet. It is defined in the ctype. h header file.
We can capitalize each word of a string by the help of split() and substring() methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or charAt() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With