#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool ifFront(string key, int command_line);
string Uppercase(string front);
int Repeated(string characters);
int main(int argc, string argv[])
{
// 1,用户按照恰当的格式输入,plaintext[i] = argv[(plaintext[i]-65)](uppercase)
// 2,按照恰当格式plaintext[i] = argv[plaintext[i]-97](lowercase)
// 3,用户输入非字母符号时,不做任何处理
// test
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
string afterFront = Uppercase(argv[1]);
if (strlen(argv[1]) == 26)
{
if (!ifFront(afterFront, argc))
{
printf("key must only contain alphabetic characters\n");
return 1;
}
else if (!Repeated(afterFront))
{
printf("key must not cantain repeated characters\n");
return 1;
}
}
//正确情况时
if (ifFront(afterFront, argc))
{
string plaintext = get_string("plaintext:");
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (plaintext[i] >= 'a' && plaintext[i] <= 'z')//利用ASCII表的值减去特定值为0,按顺序排列一个个替换掉
{
plaintext[i] = tolower(argv[1][plaintext[i] - 97]);//还给他小写
}
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')
{
plaintext[i] = argv[1][plaintext[i] - 65];
}
}
printf("ciphertext: %s\n", plaintext);
return 0;
}//这里的判断可以和上面一起处理的,但我后来才知道要处理上面那两种情况
else if (strlen(argv[1]) != 26 && argc == 2)
{
printf("Key must contain 26 characters.\n");
return 1;
}
else if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else
{
return 1;
}
}
// create Uppercase,大写字母
string Uppercase(string front)
{
for (int i = 0, n = strlen(front); i < n; i++)
{
front[i] = toupper(front[i]);
}
return front;
}
// create ifFront function and if 26 and just one prompt
bool ifFront(string key, int command_line)//是字母且个数为26时
{
// its length 26? and command-line just once
if (strlen(key) == 26 && command_line == 2)//当是字母时就累加,为26时就是我们所要的
{
int sum = 0; // Number of records for fronts
// if just fonts
for (int i = 0, n = strlen(key); i < n; i++)
{
if (key[i] >= 'A' && key[i] <= 'Z')
{
sum++;
}
if (sum == 26)
{
return true;
}
}
return false;
}
return false;
}
//检查字母是否重复
int Repeated(string characters)//先复制一个,再将原来的和新的一个个比较,从新的第一个比较旧的
{
int repeated[26];
for (int i = 0; i < 26; i++)
{
repeated[i] = characters[i];
}
for (int i = 0; i < 26; i++)//从第二个开始与它本身一个个比较,如果从第一个开始就是错的
{
for (int j = i + 1; j < 26; j++)
{
if (repeated[i] == characters[j])
{
return false;
}
}
}
return true;
}
CS50X week2 Arrays Problem Set 2 Substitution, if feeling more comfortable
最新推荐文章于 2024-07-19 22:36:19 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)