toupper the vowels to lower consonant hlp!

Aug 8, 2009 at 3:02am
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
#include <iostream.h>
#include <ctype.h>

int main()
{
  char *p;
  int i;
  char str[80];
    cout<<"input a tring: ";
  cin.get(str,80);


  p = str;

  for(i = 0; p[i]; i++) {
     if(isupper(p[i]))
        p[i] = tolower(p[i]);
     else if(islower(p[i]))
        p[i] = toupper(p[i]);
  }

  cout << "Inverted-case string: " << str;

  return 0;
}



toupper the vowels to lower consonant hlp!
Aug 8, 2009 at 5:45am
your code works fine, now all you have to do is check for vowels (because they are less than consonants in the alphabet). I'd have done it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//...
for(int i = 0; str[i]; i++)
  {
	str[i] = tolower(str[i]); //everything to lower, to avoid checking for upper letters***
	switch(str[i])                //more efficient than if-else ladder
	{
		case 'a': str[i] = toupper(str[i]); break;
                case 'e': str[i] = toupper(str[i]); break;
		case 'i': str[i] = toupper(str[i]); break;
		case 'o': str[i] = toupper(str[i]); break;
		case 'u': str[i] = toupper(str[i]); break;
                //i passed the 'y' - is it a vowel or consonant in english alphabet? :-)
		default: str[i] = tolower(str[i]); break;
	}
  }
//...
//*** - IMO this code a bit slower if i didn't check for upper letters, that's only my laziness 
Last edited on Aug 8, 2009 at 5:46am
Aug 8, 2009 at 8:32am
You can reduce the switch:
1
2
3
4
5
6
7
8
9
10
11
switch(str[i])
 {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u': 
            str[i] = toupper(str[i]); break;
      default: 
            str[i] = tolower(str[i]); break;
}
Or have a single if:
1
2
3
4
if ( str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' )
     str[i] = toupper(str[i]);
else
      str[i] = tolower(str[i]); break;
Or put all that in a single statement using the conditional operator:
str[i] = ( str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ) ? toupper(str[i]) : tolower(str[i]);
Topic archived. No new replies allowed.