Reputation: 825
How does this C/C++ code work? I understood most of it but not the part specified below:
c2= (c1>='a' && c1<='z') ? ('A'+c1-'a'):c1
Especially this part:
('A'+c1-'a')
What is this part of the code doing?
Both c1
and c2
have type char
.
Upvotes: 5
Views: 3073
Reputation: 62472
The code converts a lower case character to upper case. If the character isn't lower case then it returns the original character.
The expression ('A'+c1-'a')
does the conversion. c1-a
will give the 0-based position of the character within the alphabet. By adding this value to A
you will get the upper case equivilant of c1
.
Update: if c1
is 'b' then the expression c1-'a'
would give 1, which is the 0-based position of 'b' in the alphabet' Adding 1 to 'A' will then give 'B'
Upvotes: 10
Reputation: 2397
char are just integer numbers. You can add do classic operations on them.
The operation will transform (if needed) a lower case char c1 into upper case char. But it is tricky and relies on the ASCII encoding to work and may not work with some specific local.
Instead I recommend using std::toupper, which takes into account the current local to perform the operation
Upvotes: 1
Reputation: 99094
This part:
('A'+c1-'a')
changes c1
from lower case to upper case.
The whole statement:
c2= (c1>='a' && c1<='z') ? ('A'+c1-'a'):c1
says "if c1 is lower case, change it to upper case and assign that to c2; otherwise, just assign c1 to c2."
Upvotes: 2