凯撒哈佛CS50X

时间:2018-07-08 11:51:33

标签: c cs50 caesar-cipher

这是pset2的早期版本,凯撒。我已经弄清楚了如何加密,但是在弄清楚如何将ASCII码转换为实际字母时遇到了困难。有人可以帮忙吗?

for (i = 0, n = strlen(plain); i < n; i++)
{
    if (isalpha (plain [i]))
    {
        index = (int) plain [i] - 65;
        cypher = ((index + key) % 26) + 65;
    }

}

1 个答案:

答案 0 :(得分:1)

您的代码未考虑字母的小写部分。 要解决此问题,您可以执行以下操作:

//encrypts in place; I've replaced the magic numbers with their char-literal-based derivations
void encrypt(char *plain, int key)
{
    #define cypher plain[i]
    size_t i, n, index;
    for (i = 0, n = strlen(plain); i < n; i++)
    {
        if (isupper (plain [i]))
        {
            index = plain [i] - 'A';
            cypher = ((index + key) % ('Z'-'A'+1) ) + 'A';
        }else if(islower(plain[i])){
            index = plain [i] - 'a';
            cypher = ((index + key) % ('z'-'a'+1)) + 'a';
        }else 
            cypher=plain[i];
    }
}

或者,如果您将自己限制为ASCII,则可以通过替换基于语言环境的ctype宏来加快处理速度 与简单的字符比较。如果您还愿意接受[\]^ _作为编码源/目标 ASCII中A-Z和a-z范围内的字符,您可以进一步简化为

void encrypt(char *plain, int key)
{
    #define cypher plain[i]
    size_t i, n, index;
    for (i = 0, n = strlen(plain); i < n; i++)
    {
        if(plain[i] >= 'A' && plain[i] <='z'){
            index = plain [i] - 'A';
            cypher = ((index + key) % ('z'-'A'+1) ) + 'A';
        } else cypher=plain[i];
    }
}

用法示例(任一版本):

int main(int c, char **v)
{
    char s[]="Hello, World!";
    encrypt(s,3);
    puts(s);
    encrypt(s,-3);
    puts(s);
}

样品运行:

$ ./a.out
Khoor, Zruog!
Hello, World!