数据结构—文本串加密

/*
一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:
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;
}

运行结果:


  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值