0

checking if input has the same characters

Hey guys, I'm working on a script that ciphers your input, but before you put your input in, you have to provide a key; ./substitution VcHpRZGJnTLSkFBDqWAXeUYMOI. One of the checks is to make sure the key doesn't have the same letter. I had to use someone else's code to check this. I couldn't figure it out. There's one line in there I can't understand; "if(usedChar[substitution[i] - 'A'] == true)". I don't understand how the minus capital "A" works? Any clarity on this would be appreciated. Thank you! int main(int argc, string argv[]) { // Making sure two aruments are inputed if (argc != 2) { printf("Usage: %s key\n", argv[0]); return 1; } // Making sure the input has 26 characters else if (strlen(argv[1]) != 26) { printf("Key must contain 26 characters.\n"); return 1; } string substitution = argv[1]; char key[26]; bool usedChar[26]; for (int i = 0; i < 26; i++) { usedChar[i] = false; } for (int i = 0; i < 26; i++) { if (isalpha(substitution[i])) { if (isupper(substitution[i])) { if(usedChar[substitution[i] - 'A'] == true) { printf("Duplicate key: %c\n", substitution[i]); return 1; } else { usedChar[substitution[i] - 'A'] = true; key[i] = substitution[i] -'A'; } } else { if (islower(substitution[i])) { if(usedChar[substitution[i] - 'a'] == true) { printf("Duplicate key: %c\n", substitution[i]); return 1; } else { usedChar[substitution[i] - 'a'] = true; key[i] = subst

30th Sep 2020, 2:02 AM
David
David - avatar
2 Respostas
+ 2
Characters are in fact just numbers. Which is why you can do char c = 5; char d = 'X'; There is a translation table that tells us which letter is which number - it is called ASCII and if you google "ASCII table" it will pop right up. Note especially that the character '3' for example does not have the number 3. 'A' is 65. Now, usedChar is an array with 26 entries, one for each letter, and you can use `usedChar[0]` through `usedChar[25]`. However, if you plug in the letter 'C' in there that would be `usedChar['C'] == usedChar[67]` which is out of bounds. So subtracting 'A' is a common technique to move the alphabet back towards 0 so to say. Try it out, look up 'F' and 'A' in the ASCII table and subtract their numbers. Note that this can be unsafe to do, if you subtract 'A' from non-letters you can get negative numbers, hence all the `isalpha` and `islower` checks in the code.
30th Sep 2020, 2:58 AM
Schindlabua
Schindlabua - avatar
+ 1
Schindlabua thank you so much for take the time to explain this. i get it now. really appreciate it!!
30th Sep 2020, 4:00 PM
David
David - avatar