/**
* 实验题目:
* 文本串加密和解密程序
* 实验目的:
* 掌握串的应用算法设计
* 实验内容:
* 一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:
* a b c d e f g h i j k l m n o p q r s t u v w x y z
* n g z q t c o b m u h e l k p d a w x f y i v r s j
* 则字符串"encrypt"被加密为"tkzwsdf"。
* 编写一个程序,将输入的文本串进行加密后输出,然后进行解密并输出。
*/
#include <stdio.h>
#define MAX_SIZE 100
typedef struct
{
char data[MAX_SIZE]; // 串中字符
int length; // 串长
}SqString; // 声明顺序串类型
SqString A, B;
/*-----------------将字符串常量赋给串s--------------------*/
static void str_assign(SqString &s, char cstr[])
{
int i;
for(i = 0; cstr[i] != '\0'; i++)
s.data[i] = cstr[i];
s.length = i;
}
/*-----------------销毁串--------------------*/
static void destroy_str(SqString &s)
{
}
/*-----------------输出串s--------------------*/
static void disp_str(SqString s)
{
int i;
if(s.length > 0)
{
for(i = 0; i < s.length; i++)
printf("%c", s.data[i]);
printf("\n");
}
}
/*--------------------------返回加密串--------------------------*/
static SqString encrypt_str(SqString p)
{
int i = 0;
int j;
SqString q; // 返回的加密字符串
while(i < p.length)
{
for(j = 0; p.data[i] != A.data[j]; j++); // 空语句
if(j >= p.length) // 在A串中未找到p.data[i]字母
q.data[i] = p.data[i];
else // 在A串中找到p.data[i]字母
q.data[i] = B.data[j];
i++;
}
q.length = p.length;
return q;
}
/*------------------------解密字符串---------------------------*/
static SqString unencrypt_str(SqString q)
{
int i = 0;
int j;
SqString p; // 返回的原串
while(i < q.length)
{
for(j = 0; q.data[i] != B.data[j]; j++); // 空语句
if(j >= q.length) // 在B串中未找到q.data[i]字母
p.data[i] = q.data[i];
else // 在B串中找到q.data[i]字母
p.data[i] = A.data[j];
i++;
}
p.length = q.length;
return p;
}
int main(int argc, char *argv[])
{
SqString p, q;
int ok = 1;
str_assign(A, "abcdefghijklmnopqrstuvwxyz"); // 建立A串
str_assign(B, "ngzqtcobmuhelkpdawxfyivrsj"); // 建立B串(字母映射表)
char str[MAX_SIZE];
printf("\n");
printf("输入原文串:");
gets(str); // 获取用户输入的原文串
str_assign(p, str); // 建立p串
printf("加密解密如下:\n");
printf(" 原文串:");
disp_str(p);
q = encrypt_str(p); // p串加密产生q串
printf(" 加密串:");
disp_str(q);
p = unencrypt_str(q); // q串解密产生p串
printf(" 解密串:");
disp_str(p);
printf("\n");
destroy_str(p);
destroy_str(q);
return 0;
}
测试结果:
输入原文串:abcdef
加密解密如下:
原文串:abcdef
加密串:ngzqtc
解密串:abcdef