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
.
Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language. In character arithmetic character converts into integer value to perform task. For this ASCII value is used. It is used to perform action the strings.
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.
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'
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."
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With