/*
* Copyright (c) 2015, 烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:main.cpp,sqstring.cpp,sqstring.h
* 作者:张志康
* 完成日期:2015年10月23日
* 版本号:vc++6.0
*
* 问题描述:一个文本串可用事先编制好的字符映射表进行加密。例如,设字符映射表为:
<code class="hljs has-numbering">abcdefghijklmnopqrstuvwxyz ngzqtcobmuhelkpdawxfyivrsj</code>
* 输入描述:字符串“lao he jiao shu ju jie gou”
* 程序输出:被加密为“enp bt umnp xby uy umt opy”。
*/
代码: 头文件sqstring.h见顺序串算法库。
main.cpp
#include <stdio.h>
#include "sqString.h"
SqString A,B; //用于存储字符映射表
SqString EnCrypt(SqString p)
{
int i=0,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;
}
SqString UnEncrypt(SqString q)
{
int i=0,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()
{
SqString p,q;
StrAssign(A,"abcdefghijklmnopqrstuvwxyz"); //建立A串
StrAssign(B,"ngzqtcobmuhelkpdawxfyivrsj"); //建立B串
char str[MaxSize];
printf("\n");
printf("输入原文串:");
gets(str); //获取用户输入的原文串
StrAssign(p,str); //建立p串
printf("加密解密如下:\n");
printf(" 原文串:");
DispStr(p);
q=EnCrypt(p); //p串加密产生q串
printf(" 加密串:");
DispStr(q);
p=UnEncrypt(q); //q串解密产生p串
printf(" 解密串:");
DispStr(p);
printf("\n");
return 0;
}
运行结果:
学习总结: