/*
这个问题的最后部分就是编写函数:
void decrypt( char *data, char const *key );
它接受一个加密过的字符串为参数, 它的任务是重现原来的信息. 除了它是用于揭秘之外, 它的工作原理应该与encrypt 相同
*/
void decrypt( char *data, char const *key )
{
/* offset: data 中某个字母在key 中的偏移量( 即下标 ) */
char offset;
char const *const keyMark = key;
/*
* 遍历data, 直到遇见NUL字符
*
* 如果data 中某个字符是大写字母, 记作原字母, 就遍历key 直到遇见原字母对应的小写字母形式, 记下这个小写字母在key 中的偏移量offset
* 'A' + offset 就是解密后的字母
*
* 如果data 中某个字符是小写字母, 记作原字母, 就遍历key 直到遇见原字母, 记下原字母在key 中的偏移量offset
* 'a' + offset 就是解密后的字母
*
* 如果data 中某个字符既不是大写字母, 又不是小写字母, 无需解密
*/
for( ; *data != '\0'; ++data )
{
if( *data >= 'A' && *data <= 'Z' )
{
for( key = keyMark, offset = 0; *key != *data + 32; ++key )
{
++offset;
}
*data = 'A' + offset;
}
else if( *data >= 'a' && *data <= 'z' )
{
for( key = keyMark, offset = 0; *key != *data; ++key )
{
++offset;
}
*data = 'a' + offset;
}
}
return;
}
#include <stdio.h>
int main( void )
{
char data_1[] = "TPPTAD TP ITVH";
char *key = "trailbzescdfghjkmnopquvwxy";
printf( "密钥key: %s\n\n", key );
printf( "解密前: %s\n", data_1 );
decrypt( data_1, key );
printf( "解密后: %s\n\n", data_1 );
char data_2[] = "Tff thsgtfo tnl lmqtf, rqp ojgl thsgtfo tnl gjnl lmqtf peth jpelno!";
printf( "解密前: %s\n", data_2 );
decrypt( data_2, key );
printf( "解密后: %s\n\n", data_2 );
return 0;
}
程序运行结果: