Capitalize String

I was wondering what were different ways to capitalize a string. This is one way I did it.
void capitalize(char letters[36]){ // function prototype
//char letters[] = "This sentence MUST be all capitals!";
for ( int i=0; i<32; i++){
if (letters[i] >='a')

letters[i]-= 32;
cout<< letters[i] ;
}
}
and then we called the function in main, but I was curious what if I wanted to only capitalize the first letters of each word. What would I do then?
Thanks for your help in advance
hmm - if i remember it correctly there a function "toupper"

1
2
string str = "something";
str[0] = toupper(str[0]);
a) there is toupper() function in cctype library.
b) you can iterate over all character in string and apply said function to them:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
#include <cctype>

int main()
{
    std::string str = "I am a string";
    for(auto& x: str)
        x = toupper(x);
    std::cout << str;
}
or with c-strings:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstring>
#include <cctype>

int main()
{

    char str[30] = "I am a string";
    for(int i = 0; i < strlen(str); ++i)
        str[i] = toupper(str[i]);
    std::cout << str;
}
Last edited on
There's also a to_upper for strings in boost, if you want a shortcut

1
2
3
4
5
6
7
8
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
    std::string str = "I am a string";
    boost::algorithm::to_upper(str);
    std::cout << str << '\n';
}

online demo: http://liveworkspace.org/code/4dL4Mi

And, for the crazy people like me, there is a toupper for strings in the standard library as well

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include <locale>

int main()
{
    std::string str = "I am a string";
    std::use_facet<std::ctype<char>>(std::locale()).toupper(&str[0], &str[0] + str.size());
    std::cout << str << '\n';
}

online demo: http://ideone.com/uPthJI
Topic archived. No new replies allowed.