/*
一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:
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 <iostream>
#include <stdio.h>
#include <cstring>
#define MaxSize 100
using namespace std;
typedef struct
{
char data[MaxSize];
int length;
} SqString;
SqString A,B;
void StrAssign(SqString &s,char cstr[]) //将一个字符串常量赋给串s,即生成一个其值等于cstr的串s
{
int i;
for(i=0; cstr[i]!='\0'; i++)
s.data[i]=cstr[i];
s.length=i;
}
void DispStr(SqString s) //输出串的所有元素值
{
int i;
if(s.length>0)
{
for(i=0; i<s.length; i++)
cout<<s.data[i];
cout<<endl;
}
}
SqString EnCrypt(SqString p) //加密
{
SqString q;
q.length=p.length;
for(int i=0;i<p.length;i++)
{
int j=0;
while(p.data[i]!=A.data[j]&&j<A.length)
j++;
if(j>=A.length)
q.data[i]=p.data[i];
else
q.data[i]=B.data[j];
}
return q;
}
SqString UnEnCrypt(SqString p) //解密
{
SqString q;
q.length=p.length;
for(int i=0;i<p.length;i++)
{
int j=0;
while(p.data[i]!=B.data[j]&&j<B.length)
j++;
if(j>=B.length)
q.data[i]=p.data[i];
else
q.data[i]=A.data[j];
}
return q;
}
int main()
{
SqString p,q;
char a[MaxSize];
StrAssign(A,"abcdefghijklmnopqrstuvwxyz");
StrAssign(B,"ngzqtcobmuhelkpdawxfyivrsj");
cout<<"\n输入原文串:";
gets(a);
StrAssign(p,a);
cout<<"加密解密如下:"<<endl;
cout<<" 原文串:";
DispStr(p);
q=EnCrypt(p);
cout<<" 加密串:";
DispStr(q);
p=UnEnCrypt(q);
cout<<" 解密串:";
DispStr(p);
return 0;
}
运行结果: