Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Created April 19, 2020 21:04
Show Gist options
  • Save voidnerd/3fdab5b9d10469225247f1c8057d0e2d to your computer and use it in GitHub Desktop.
Save voidnerd/3fdab5b9d10469225247f1c8057d0e2d to your computer and use it in GitHub Desktop.
CS50's Problem Set 2 - Substitution
#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
bool isAlpha(string key);
bool hasDuplicates(string key);
int main(int argc, string argv[])
{
if (argc != 2 || !isAlpha(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}
else if (strlen(argv[1]) < 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
else if (hasDuplicates(argv[1]))
{
printf("Key must not contain duplicates.\n");
return 1;
}
else
{
string key = argv[1];
printf("%s \n", key);
string plaintext = get_string("Plaintext: ");
printf("ciphertext: ");
for (int i = 0, len = strlen(plaintext); i < len; i++)
{
if (isalpha(plaintext[i]))
{
if (isupper(plaintext[i]))
{
char letter = key[ ((plaintext[i] - 65) % 26)];
if(islower(letter))
{
printf("%c", letter - 32);
}else
{
printf("%c", letter);
}
}
else
{
char letter = key[((plaintext[i] - 97) % 26)];
if (isupper(letter))
{
printf("%c", (int)letter + 32);
}else
{
printf("%c", letter);
}
}
}
else
{
printf("%c", plaintext[i]);
}
}
printf("\n");
return 0;
}
}
bool isAlpha(string key)
{
for (int i = 0; i < strlen(key); i++)
{
if (!isalpha(key[i]))
{
return false;
}
}
return true;
}
bool hasDuplicates(string key)
{
for (int i = 0, len = strlen(key); i < len; i++)
{
for (int j = 0; j < len; j++)
{
if (key[i] == key[j] && i != j)
{
return true;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment