user3896430
user3896430

Reputation: 11

Lower case to upper case without toupper

Can someone tell me why the line

  s[i]=s[i]-'a'+'A';

does the job of converting lower case to upper case? More specifically, I do not understand why 'a' and 'A' get substituted by the corresponding characters from string s.

string s="Print My Name";

for (int i=0; i<s.length(); i++)
  {
    if (s[i]>='a' && s[i]<='z')
    {
       s[i]=s[i]-'a'+'A';

    }
  }

Upvotes: 0

Views: 3612

Answers (3)

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

The expression

s[i]=s[i]-'a'+'A'

in C++ (and C as well) means

s[i]=s[i]-<code of character a>+<code of character A>

this, together with the assumption that all lowercase letter are consecutive, and all uppercase letters are consecutive makes it working.

Of course normally the assumptions above are valid for English characters only.

Upvotes: 2

Puppy
Puppy

Reputation: 146910

does the job of converting lower case to upper case?

It doesn't. Try passing something like "naïve" in. The C and C++ Standards do not specify any genuinely useful string manipulation functions, although some implementations extend them to be more useful.

If you want string handling functions that actually work, albeit with an interface less friendly than a primed nuclear warhead, you can look at ICU.

Upvotes: 7

Sean
Sean

Reputation: 62472

The expression:

s[i]-'a'

Returns the zero based position of the character within the alphabet. Then adding 'A' adds that position to upper case 'A' given the upper case equivilant of s[i].

Upvotes: -1

Related Questions