Skip to content

Instantly share code, notes, and snippets.

@cherylli
Created November 24, 2020 10:57
Show Gist options
  • Save cherylli/dad494556705a26e2a6118a344cd4836 to your computer and use it in GitHub Desktop.
Save cherylli/dad494556705a26e2a6118a344cd4836 to your computer and use it in GitHub Desktop.
CS50x 2020 Problem Set 2 Substitution
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "cs50.h"
int main(int argc, string argv[])
{
if (argc < 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
string key = argv[1];
//char plain_text[] = "Hello, world";
if (strlen(key) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
//iterate through the string, check if there's non alphabetic char isalpha, convert key into lowercase (tolower())
for (int i = 0; i < strlen(key); i++)
{
if (isalpha(key[i]) == 0)
{
printf("Key must only contain alphabets.\n");
return 1;
}
//loop the string again to check if there's repeated char
for (int j = 0; j < strlen(key); j++)
{
if (tolower(key[i]) == tolower(key[j]) && i != j)
{
printf("Each character can only appear once.\n");
return 1;
}
else
{
key[i] = tolower(key[i]);
}
}
}
// get user input
string plain_text = get_string("plaintext: ");
printf("ciphertext: ");
for (int i = 0; i < strlen(plain_text); i++)
{
if (plain_text[i] >= 97 && plain_text[i] <= 122)
{
//lower case
printf("%c", key[plain_text[i] - 'a']);
}
else if (plain_text[i] >= 65 && plain_text[i] <= 90)
{
//upper case
printf("%c", key[plain_text[i] - 'A'] - 32);
}
else
{
// do nothing, just print the character
printf("%c", plain_text[i]);
}
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment