How would I change certain letters in a string to uppercase?

For example if I had the user input "whats on television"

How would I make the output become Whats On Television?
Tried to explain it the best I could using the comments. It's a fairly straightforward method. I haven't tested it, but it should work without any issues.

The ASCII table I used can be found at http://www.asciitable.com/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Traverse through the entire string (noted as "str")
for(unsigned int index = 0; index < strlen(str); index++) {
	static bool bMakeUppercase = true; // By default we make the first letter uppercase (assuming it's even a letter!)

	// Spaces indicate new words
	if(str[index] == ' ') {
		bMakeUppercase = true;
	}
	
	// If we have encountered a space, then we need to make the letter capitalized.
	// The letter is also lowercase a-z
	if(bMakeUppercase && str[index] >= 'a' && str[index] <= 'z') {
		bMakeUppercase = false;

		str[index] = str[index] - 32; // Difference from 'a' to 'A' is -32 (ASCII tables come in handy here!)
	}
}


P.S: First post on the forums, woohoo!
Last edited on
Works perfectly, thanks a lot I didn't think of that!
Also I was wondering are there many ways to go about doing this?
An STL algorithm way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

struct totitle_t
  {
  bool is_make_upper;
  totitle_t():
    is_make_upper( true )
    { }
  char operator () ( char c )
    {
    bool was_make_upper = is_make_upper;
    is_make_upper = isspace( c );
    return was_make_upper
         ? toupper( c )
         :          c;
    }
  };

int main()
  {
  string s;
  cout << "Enter some text to \"Title Case\".\n> ";
  getline( cin, s );

  transform( s.begin(), s.end(), s.begin(), totitle_t() );

  cout << s << endl;

  return 0;
  }
Topic archived. No new replies allowed.