簡體   English   中英

C語言中凱撒密碼程序的高級思考

[英]Advanced thinking on Caesar Cipher program in C

#include <stdio.h>

void caesar (char cipher[], int shift);

int main ()
{

char cipher[200];
int shift;

printf("Enter text to be encrypted (in small letter): ");
gets(cipher);

printf("Number of shift to right? : ");
scanf("%d", &shift);

caesar (cipher, shift);

return 0;
}

void caesar (char cipher[], int shift)
{
int i = 0;

while (cipher[i] != '\0')
{
    if ((cipher[i] + shift) >= 97 && (cipher[i] + shift) <= 122)
    {
        cipher[i] += (shift);
    }
    else
    {
        cipher[i] += (shift - 25);
    }
    i++;
}
printf("%s", cipher);
}

如何忽略空格的操作? 我的意思是,我想在轉換/解密的字符串中添加空格。 當我運行該程序時,它將消失加密字符串中的空格。 我怎樣才能做到這一點? 假設如果右移1,則“這是一支筆”將變為:“ uijt jt b qfo”。

轉換前,應檢查字符是否為字母。 您的代碼將轉移所有內容,然后僅檢查字符是否為有效字母以檢測換行。 (它也不會使修飾和空格消失,它將它們轉換為ASCII值低於32的不可打印字符。)

您還可以通過使用模運算符來強制正確的換行:

void caesar(char cipher[], int shift)
{
    char *p = cipher;

    while (*p)
    {
        if ('a' <= *p && *p <= 'z') {
            *p = 'a' + (*p - 'a' + shift) % 26;
        }
        p++;
    }
}

如果要自動檢測到移位,只需對所有26種可能的移位使用蠻力並檢查常見的預期子字符串:

int autocaesar(char cipher[])
{
    int shift = 0;

    while (shift < 26) {
        if (strstr(cipher, "the")) return shift;
        if (strstr(cipher, "this")) return shift;
        if (strstr(cipher, "that")) return shift;

        caesar(cipher, 1);
        shift++;
    }

    return -1;
}

函數strstr<string.h>並在字符串中找到子字符串。 這在這里非常粗略地完成:並不強制要求"the"本身就是一個詞。 另外,檢查是區分大小寫的。

請注意,由於原始字符串將連續移動,因此密碼一次只能移動一個字符。 如果未找到任何內容,則將其包裹起來以包含原始字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM