Created
February 4, 2022 09:17
-
-
Save Alexandr6363/773db48d491978097f2b11c46c83b4ca to your computer and use it in GitHub Desktop.
CS50 (cs50x) pset2 Substitution Solution 2022
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 <ctype.h> | |
#include <cs50.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
//prototype | |
string valid_key(string key); | |
string do_text(string start_text, string key); | |
void swap(char *a, char *b); | |
string to_lower(string copy_key); | |
// main function | |
int main(int argc, string argv[1]) | |
{ | |
//check argument comannd string | |
if (argc == 2) | |
{ | |
string key = argv[1]; | |
//get memory to copy key | |
string copy_key = malloc(strlen(key) + 1); | |
//copy key | |
strcpy(copy_key, key); | |
//tolower copy key | |
copy_key = to_lower(copy_key); | |
//sorted key to check with etalon | |
string key_sort = valid_key(copy_key); | |
string key_etalon = "abcdefghijklmnopqrstuvwxyz"; | |
//compare sorted key with etalon | |
if (strcmp(key_sort, key_etalon) == 0) | |
{ | |
//get text | |
string start_text = get_string("plaintext: "); | |
//encryption text | |
string finish_text = do_text(start_text, key); | |
//print encrypted text | |
printf("ciphertext: %s\n", finish_text); | |
//free memory | |
free(copy_key); | |
return 0; | |
} | |
else | |
{ | |
free(copy_key); | |
printf("./substitution key\n"); | |
return 1; | |
} | |
} | |
else | |
{ | |
printf("./substitution key\n"); | |
return 1; | |
} | |
} | |
// produce lower char in copy key | |
string to_lower(string copy_key) | |
{ | |
for (int i = 0; i < strlen(copy_key); i++) | |
{ | |
copy_key[i] = tolower(copy_key[i]); | |
} | |
return copy_key; | |
} | |
// swap char in sort | |
void swap(char *a, char *b) | |
{ | |
char temp = *a; | |
*a = *b; | |
*b = temp; | |
} | |
// sort | |
string valid_key(char *word) | |
{ | |
for (unsigned int i = 0; i < strlen(word) - 1; i++) | |
{ | |
for (unsigned int j = i + 1; j < strlen(word); j++) | |
{ | |
if (word[i] > word[j]) | |
{ | |
swap(&word[i], &word[j]); // simply swap the characters | |
} | |
} | |
} | |
return word; | |
} | |
// use check to our text | |
string do_text(string start_text, string key) | |
{ | |
for (int i = 0; i <= strlen(start_text); i++) | |
{ | |
if ((start_text[i] >= 65) && (start_text[i] <= 90)) | |
{ | |
start_text[i] = toupper(key[(start_text[i] - 65)]); | |
} | |
else if ((start_text[i] >= 97) && (start_text[i] <= 122)) | |
{ | |
start_text[i] = tolower(key[(start_text[i] - 97)]); | |
} | |
else | |
{ | |
start_text[i] = start_text[i]; | |
} | |
} | |
return start_text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment