-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubstitution.c
More file actions
87 lines (59 loc) · 1.38 KB
/
substitution.c
File metadata and controls
87 lines (59 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <cs50.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
bool is_valid_key(string s); // function decl
int main(int argc, string argv[])
{
if (argc != 2) // checkm if two arguments.
{
printf("Usage: ./substitution key\n");
return 1;
}
if (!is_valid_key(argv[1])) // Check key validity.
{
puts("Key must contain 26 characters.\n");
return 1;
}
string s = get_string("plaintext: "); // User input as plaintext.
string difference = argv[1];
for (int i = 'A'; i <= 'Z' ; i++)
{
difference[i - 'A'] = toupper(difference [i - 'A']) - i ;
}
printf("ciphertext: ");
for (int i = 0, len = strlen(s); i < len; i++)
{
if (isalpha(s[i])) // check alphabates.
{
s[i] = s[i] + difference[s[i] - (isupper(s[i]) ? 'A' : 'a')];
}
printf("%c", s[i]); // prints cyohertext.
}
printf("\n");
}
bool is_valid_key(string s)
{
//int i = 0;
int len = strlen(s);
if (len != 26)
{
return false ;
}
int freq [26] = {0} ;
for (int i = 0; i < len ; i++)
{
if (!isalpha(s[i]))
{
return false;
}
int index = toupper(s[i]) - 'A';
if (freq[index] > 0)
{
return false;
}
freq[index]++;
}
return true;
}