您的位置:首页 > 其它

串的实验---字符串加密

2016-04-20 17:59 453 查看
实验要求:

一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:
abcdefghijklmnopqrstuvwxyz
ngzqtcobmuhelkpdawxfyivrsj
则字符串“abc”被加密为“ngz”。设计一个程序exp4-4.cpp将输入的文本串进行加密后输出,然后进行解密并输出。

输入代码:

#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
#define MaxSize 27
char str1[MaxSize]= {'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'};
char str2[MaxSize]= {'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'};
typedef struct
{
char data[MaxSize];
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 encryption(SqString &s)
{
for(int i=0;s.data[i]!='\0';i++)
{
for(int j=0;str1[j]!='\0';j++)
{
if(s.data[i]==str1[j])
{
s.data[i]=str2[j];
break;
}
}
}
for(int j=0; j<s.length; j++)
{
printf("%c",s.data[j]);
}
printf("\n");
}
bool decryption(SqString &s)
{
for(int i=0;s.data[i]!='\0';i++)
{
for(int j=0;str2[j]!='\0';j++)
{
if(s.data[i]==str2[j])
{
s.data[i]=str1[j];
break;
}
}
}
for(int j=0; j<s.length; j++)
{
printf("%c",s.data[j]);
}
printf("\n");
}
void DispStr(SqString s)
{
int i;
if(s.length>0)
{
for(i=0; i<s.length; i++)
{
printf("%c",s.data[i]);
}
printf("\n");
}
}
int main()
{
char str[27];
SqString SS;
cout<<"输入原文串:";
gets(str);
StrAssign(SS,str);
cout<<"加密解密如下:"<<endl;
cout<<"  原文串:";
DispStr(SS);
cout<<"  加密串: ";
encryption(SS);
cout<<"  解密串: ";
decryption(SS);
}


运行结果:




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: