Advertisement
YoungSideways

Caesar Cipher

Mar 13th, 2023
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | Cryptocurrency | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdbool.h>
  4. #include <assert.h>
  5.  
  6. bool isAlphabetValid(char* alphabet) {
  7.     assert(alphabet);
  8.     if (!*alphabet)
  9.         return false;
  10.     for (; *alphabet; alphabet++)
  11.         if (strchr(alphabet + 1, *alphabet))
  12.             return false;
  13.     return true;
  14. }
  15. bool isStringValid(char* string, char* alphabet, char* exclude) {
  16.     assert(string);
  17.     assert(alphabet);
  18.     if (!*string)
  19.         return false;
  20.    
  21.     if (exclude)
  22.         for (; *string; string++) {
  23.             if (strchr(exclude, *string))
  24.                 continue;
  25.             if (!strchr(alphabet, *string))
  26.                 return false;
  27.         }
  28.     else
  29.         for (; *string; string++)
  30.             if (!strchr(alphabet, *string))
  31.                 return false;
  32.     return true;
  33. }
  34. inline ptrdiff_t getIndex(char* string, int c) {
  35.     return strchr(string, c) - string;
  36. }
  37.  
  38. void Caesar_Cipher(char* string, char* alphabet, char* exclude, unsigned shift) {
  39.     if (!isAlphabetValid(alphabet) || !isStringValid(string, alphabet, exclude))
  40.         return;
  41.  
  42.     size_t alphabet_size = strlen(alphabet);
  43.  
  44.     if (exclude)
  45.         for (; *string; string++) {
  46.             if (strchr(exclude, *string))
  47.                 continue;
  48.             *string = alphabet[(getIndex(alphabet, *string) + shift) % alphabet_size];
  49.         }
  50.     else
  51.         for (; *string; string++)
  52.             *string = alphabet[(getIndex(alphabet, *string) + shift) % alphabet_size];
  53. }
  54.  
  55. char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  56. char exclude[] = " ,.!?";
  57.  
  58. char MyString[] = "HELLO, MY NAME IS ALEX! WHATS YOU?";
  59.  
  60. int main()
  61. {
  62.     printf("\"%s\"\n", MyString);
  63.     Caesar_Cipher(MyString, alphabet, NULL, 3);
  64.     printf("\"%s\"\n", MyString);
  65.     Caesar_Cipher(MyString, alphabet, exclude, 1);
  66.     printf("\"%s\"\n", MyString);
  67.     Caesar_Cipher(MyString, alphabet, exclude, 0);
  68.     printf("\"%s\"\n", MyString);
  69.     Caesar_Cipher(MyString, alphabet, exclude, 25);
  70.     printf("\"%s\"\n", MyString);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement