Skip to content

Instantly share code, notes, and snippets.

@iboss-ptk
Last active November 28, 2022 04:33
Show Gist options
  • Save iboss-ptk/75996e3d9a7f36f4c7705cc0b9db8c23 to your computer and use it in GitHub Desktop.
Save iboss-ptk/75996e3d9a7f36f4c7705cc0b9db8c23 to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
string key = argv[1];
if (strlen(key) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
// iterate through all key char
for (int i = 0; i < strlen(key); i++)
{
// normalize key as uppercase letters
key[i] = toupper(key[i]);
// special characters are not allowed
bool is_within_a_to_z = key[i] >= 'A' && key[i] <= 'Z';
if (!is_within_a_to_z)
{
printf("Special characters are not allowed.\n");
return 1;
}
// duplicated keys are not allowed
for (int j = 0; j < i; j++)
{
// check if any previous key char is the same as current key char
if (key[i] == key[j])
{
printf("Duplicated keys are not allowed.\n");
return 1;
}
}
}
string text = get_string("plaintext: ");
for (int i = 0; i < strlen(text); i++)
{
// substitute only alphabets
if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
{
// normalize it to upper
char normalized = toupper(text[i]);
// upper case starts at 'A' so 'A'-'A' = 0, 'B'-'A' = 1 and so on
char cipher_char = key[normalized - 'A'];
// check if plaintext char is lowercase, if so, map cipher char to lowercase
if (islower(text[i]))
{
cipher_char = tolower(cipher_char);
}
// update text[i] as cipher char
text[i] = cipher_char;
}
}
printf("ciphertext: %s\n", text);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment