Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 337
WilliamKF Avatar asked Mar 12 '13 19:03

WilliamKF


People also ask

How do you capitalize the first letter of each word in a string in C?

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.

How do you write a capital letter in C?

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.

How do you capitalize every word in a string in word?

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.


1 Answers

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.

like image 109
jerry Avatar answered Sep 18 '22 15:09

jerry