实验六 文本串的加密解密
一个文本串可用事先给定的字母映射表进行加密。例如,假设字母映射表为:
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”
要求:设计程序将输入的文本串进行加密后输出,然后进行解密并输出。
SqString.h
#define MAX_SIZE 100
typedef struct
{
char data[MAX_SIZE]; // 串中字符
int length; // 串长
}SqString; // 声明顺序串类型
void strAssign(SqString &s, char cstr[])//生成串
{
int i;
for(i = 0; cstr[i] != '\0'; i++)
s.data[i] = cstr[i];
s.length = i;
}
void DestroyStr(SqString &s)//销毁串
{
}
void DispStr(SqString s)//输出串
{
int i;
if(s.length > 0)
{
for(i = 0; i < s.length; i++)
printf("%c", s.data[i]);
printf("\n");
}
}
SqString EnCrypt(SqString &p,SqString A,SqString B)//加密
{
for(int i=0;i<p.length;i++)
{
int j=0;
while(j<A.length)
{
if(p.data[i]==A.data[j])
{
p.data[i]=B.data[j];
break;
}
else
j++;
}
}
return p;
}
SqString UnEnCrypt(SqString &p,SqString A,SqString B)//解密
{
for(int i=0;i<p.length;i++)
{
int j=0;
while(j<B.length)
{
if(p.data[i]==B.data[j])
{
p.data[i]=A.data[j];
break;
}
else
j++;
}
}
return p;
}
main.cpp
#include <iostream>
#include "SqString.h"
int main(int argc, char** argv) {
SqString p,A,B;
strAssign(A, "abcdefghijklmnopqrstuvwxyz"); // 建立A串
strAssign(B, "ngzqtcobmuhelkpdawxfyivrsj");// 建立B串(字母映射表)
char str[MAX_SIZE];
printf("请输入你需要加密的字符:") ;
gets(str);
strAssign(p,str);
printf("\n加密之后:");
EnCrypt(p,A,B);
DispStr(p);
printf("\n解密之后:");
UnEnCrypt(p,A,B);
DispStr(p);
DestroyStr(p);
DestroyStr(A);
DestroyStr(B);
return 0;
}