Advertisement
Guest User

substitution

a guest
Mar 16th, 2024
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. int main(int argc, string argv[])
  7. {
  8.  
  9. // check for 26 characters in key, check to make sure there are right amount of cmd line arguments
  10. if (argc != 2)
  11. {
  12. printf("Usage: ./substitution (key)\n");
  13. return 1;
  14. }
  15.  
  16. // is it a letter?
  17. string cipherkey = argv[1];
  18. int len = strlen(cipherkey);
  19.  
  20. for (int i = 0; i < len; i++)
  21. {
  22. if (!isalpha(cipherkey[i]))
  23. {
  24. printf("Usage: ./substitution (key)\n");
  25. return 1;
  26. }
  27.  
  28. // is it 26 characters?
  29. if (len != 26)
  30. {
  31. printf("Key must be 26 characters!\n");
  32. return 1;
  33. }
  34.  
  35. // has to be 26 diff alphabet
  36. for (int first = 0; first < len; first++)
  37. {
  38. for (int second = first + 1; second < len; second++)
  39. {
  40. if (toupper(cipherkey[first]) == toupper(cipherkey[second]))
  41. {
  42. printf("Usage: ./substitution (key)\n");
  43. return 1;
  44. }
  45. }
  46. }
  47. }
  48.  
  49. // run actual cipher decoding part
  50. string text = get_string("plaintext: ");
  51.  
  52. for (int i = 0; i < len; i++)
  53. {
  54. if (islower(cipherkey[i]))
  55. {
  56. cipherkey[i] = cipherkey[i] - 32; // difference between upper and lower case letter equivalent in ASCII ('A' - 'a' = 32 for example)
  57. }
  58. }
  59.  
  60. // final result, look for if the index is upper or lower case
  61. printf("ciphertext: ");
  62.  
  63. for (int i = 0; i < len; i++)
  64. {
  65. if (isupper(text[i]))
  66. {
  67. int upperpos = text[i] - 65;
  68. printf("%c", cipherkey[upperpos]); // print result of math, make it an index of cipher key to print later
  69. }
  70.  
  71. else if (islower(text[i]))
  72. {
  73. int lowerpos = text[i] - 97;
  74. printf("%c", cipherkey[lowerpos] + 32);
  75. }
  76. else printf("%c", text[i]);
  77. }
  78. printf("\n");
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement