数据结构之串的加密,此问题并不难,主要是串的基本应用。
#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);
}
数据结构之字符加密与解密
最新推荐文章于 2023-04-26 17:21:23 发布