我试图用这个函数用一组给定的字母(字符串b)对给定的文本(字符串a)进行加密。
它编译、运行并实际替换字母,只是方式不对。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
string replace(string a , string b);
int main(int argc, string argv[])
{
string code;
if(argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else
{
code = argv[1];
if(strlen(argv[1]) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
for(int i = 0; i < 26; i++)
{
if (isalpha(code[i]) == 0)
{
printf("Key must only contain alphabetic characters.\n");
return 1;
}
}
for(int j = 0; j < 26; j++)
{
for(int n = j + 1; n < 26; n++)
{
if(code[j] == code[n])
{
printf("Key must not contain repeated characters.\n");
return 1;
}
}
}
}
string txt = get_string("plaintext:");
printf("ciphertext: %s\n" , replace(txt , code));
return 1;
}
string replace(string a , string b)
{
string final = a;
string alpha = {"abcdefghijklmnopqrstuvwxyz"};
for (int i = 0; i < strlen(a); i++)
{
for(int n = 0; n < 26; n++)
{
if(a[i] == alpha[n])
{
final[i] = b[n];
}
}
}
return final;
}
我只是想了解它是怎么回事,以下是我的一些样本:
./substitution ytnshkvefxrbauqzclwdmipgjo
plaintext: hello
ciphertext hhbbq
当我再尝试一次时,输出是
ehbbq
哪一个是正确的,但每次我尝试都不一样。