Reputation: 43179
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?
Upvotes: 5
Views: 8598
Reputation: 11
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.
Upvotes: -1
Reputation: 108
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";
}
Upvotes: 0
Reputation: 2611
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.
Upvotes: 6