Created
May 26, 2023 11:37
-
-
Save andrija-zikovic/e1f36e159b3e94e857990edb138a1ba6 to your computer and use it in GitHub Desktop.
CS50/substitution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cs50.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <ctype.h> | |
int only_letters(string text); | |
int repeated(string text); | |
char rotate(char c, string key); | |
int main(int argc, string argv[]) | |
{ | |
if (argc != 2) | |
{ | |
printf("Usage: ./caesar key\n"); | |
return 1; | |
} | |
else if (strlen(argv[1]) < 26 || strlen(argv[1]) > 26) | |
{ | |
printf("Key must contain 26 characters.\n"); | |
return 1; | |
} | |
else if (!only_letters(argv[1])) | |
{ | |
printf("Key must contain only letters\n"); | |
return 1; | |
} | |
else if (!repeated(argv[1])) | |
{ | |
printf("Letters must not be repeted\n"); | |
return 1; | |
} | |
else | |
{ | |
string plaintext = get_string("plaintext: "); | |
printf("ciphertext: "); | |
for (int i = 0; i < strlen(plaintext); i++) | |
{ | |
printf("%c", rotate(plaintext[i], argv[1])); | |
} | |
printf("\n"); | |
} | |
} | |
int only_letters(string text) | |
{ | |
for (int i = 0; text[i]!='\0'; ++i) | |
{ | |
if(!isalpha(text[i])) | |
{ | |
return 0; | |
} | |
} | |
return 1; | |
} | |
int repeated(string text) | |
{ | |
int count = 0; | |
for (int i = 0; i < strlen(text); ++i) | |
{ | |
for (int j = 0; j < strlen(text); ++j) | |
{ | |
if (toupper(text[i]) == toupper(text[j])) | |
{ | |
count ++; | |
} | |
} | |
} | |
if (count != 26) | |
{ | |
return 0; | |
} | |
else | |
{ | |
return 1; | |
} | |
} | |
char rotate(char c, string key) | |
{ | |
for (int i = 0; i <= 25; i++) | |
{ | |
if(isalpha(c)) | |
{ | |
if (isupper(c)) | |
{ | |
char new = key[(c - 65)]; | |
return toupper(new); | |
} | |
else | |
{ | |
char new = key[(c - 97)]; | |
return tolower(new); | |
} | |
} | |
else | |
{ | |
return c; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment