CS50x Substitution

Photo by Raphael Schaller on Unsplash
$ ./substitution YTNSHKVEFXRBAUQZCLWDMIPGJO
plaintext: HELLO
ciphertext: EHBBQ
// Validate the key
// Check argc for 2 and argv[1] for len and non-alpha chars or repetitions
// Ask user for plain text and store it
// Replace each char in text with the char with same index in key. Keep case and non-alpha
// Ciphers a text using substitution cipher#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
// Prototype functions
void subs(char *, char*);
int main(int argc, char *argv[])
{
//validate key here

string text = get_string("Enter Text: ");
subs(text, argv[1]);
}
void subs(char *t, char *k)
{

}
int main(int argc, char *argv[])
{
//validate key here
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
if (strlen(argv [1]) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
for (int i = 0; i < strlen(argv[1]); i++)
{
if (isalpha(argv[1][i]) == 0)
{
printf("Key must only contain alphabetic characters. \n");
return 1;
}
for (int r = i + 1; r < strlen(argv[1]); r++)
{
if (toupper(argv[1][r]) == toupper(argv[1][i]))
{
printf("Key must only contain one of each alphabetic character. \n");
return 1;
}
}
}
~/pset2/substitution/ $ ./substitution VcHpRzGjNtLsKfBdQwAxEuYmOi
Enter Text:
~/pset2/substitution/ $ ./substitution VcHpRzGjNtLsKfBdQwAxEuYmOiL
Key must contain 26 characters.
~/pset2/substitution/ $ ./substitution VcHpRzGjNtLsKfBdQwAxEuYmO5
Key must only contain alphabetic characters.
~/pset2/substitution/ $ ./substitution VcHpRzGjNtLsKfBdQwAxEuYmOv
Key must only contain one of each alphabetic character.
~/pset2/substitution/ $ ./substitution VcHpRzGjNtLsKfBdQwAxEuYmOi o
Usage: ./substitution key
void subs(char *t, char *k)
{
printf("ciphertext: ");
for (int i = 0; i < strlen(t); i++)
{
if (isalpha(t[i]) != 0)
{
if (isupper(t[i]) != 0)
{
int index = t[i] - 'A';
printf("%c", toupper(k[index]));
}
else
{
int index = t[i] - 'a';
printf("%c", tolower(k[index]));
}
}
else
{
printf("%c", t[i]);
}
}
printf("\n");
}
Results generated by style50 v2.7.4
Looks good!
Results for cs50/problems/2020/x/substitution generated by check50 v3.1.2
:) substitution.c exists
:) substitution.c compiles
:) encrypts "A" as "Z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
:) encrypts "a" as "z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
:) encrypts "ABC" as "NJQ" using NJQSUYBRXMOPFTHZVAWCGILKED as key
:) encrypts "XyZ" as "KeD" using NJQSUYBRXMOPFTHZVAWCGILKED as key
:) encrypts "This is CS50" as "Cbah ah KH50" using YUKFRNLBAVMWZTEOGXHCIPJSQD as key
:) encrypts "This is CS50" as "Cbah ah KH50" using yukfrnlbavmwzteogxhcipjsqd as key
:) encrypts "This is CS50" as "Cbah ah KH50" using YUKFRNLBAVMWZteogxhcipjsqd as key
:) encrypts all alphabetic characters using DWUSXNPQKEGCZFJBTLYROHIAVM as key
:) handles lack of key
:) handles invalid key length
:) handles invalid characters in key
:) handles duplicate characters in key
:) handles multiple duplicate characters in key