I don't know what "return ch[c-'A'];&return ch[c-'1' 26]; "doing. The following are some code for uva401 - Palindromes in c .
char ch[36]={'A',' ',' ',' ','3',' ',' ','H','I','L',
' ','J','M',' ','O',' ',' ',' ','2','T',
'U','V','W','X','Y','5','1','S','E',' ',
'Z',' ',' ','8',' '};
char rev(char);
char rev(char c){
if (isalpha(c)){
return ch[c-'A'];//this line I don't know what it means.
} else {
return ch[c-'1' 26];//this line I don't know what it means.
}
}
CodePudding user response:
Char variables in C are also represented by ASCII values for example, 'A' in ASCII is 65. So if char c = 'B' which equals 65 in ASCII increasing orderly in the alphabetical order, c - 'A' would mean 66 - 65 which equals 1. This value of 1 is then used as an index of the array ch to traverse the element at that index.
char ch[36]={'A',' ',' ',' ','3',' ',' ','H','I','L',
' ','J','M',' ','O',' ',' ',' ','2','T',
'U','V','W','X','Y','5','1','S','E',' ',
'Z',' ',' ','8',' '};
int c = 'B';
cout << ch[c - 'B']; //Output: A
ASCII chart for all char variables
CodePudding user response:
Characters in C are represented by 8-bit integers (putting aside anything more complex than ASCII for now). For instance, 'a'
is 97
, and 'z'
is 122
.
We can do math with these, and they are automatically coerced into integers. Arrays are indexed by numbers, so we can use the result of this math to lookup an entry in an array.
Consider that 'A'
is 65
. If we subtract that from another capital character, we'll be left with how many characters into the alphabet we are. So 'E' - 'A'
evaluates to 4
.