文本串加密和解密程序

版权声明:本文为博主原创文章,转载请注明出处( • ̀ω•́ )✧ https://blog.csdn.net/wangws_sb/article/details/83780425

目的:掌握串的应用算法设计。

内容:一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:

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"。编写一个程序exp4-4.cpp,将输入的文本串加密后输出,然后进行解密并输出。

题解:字符串的模拟过程。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char s1[30]= {'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 s2[30]= {'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'};
char p1[30],p2[30];
int main()
{
    int n;
    char str[10000];
    for(int i=0; i<26; i++)
    {
        p1[s1[i]-'a']=s2[i];//加密过程映射
        p2[s2[i]-'a']=s1[i];//解密过程映射
    }
    cout<<"请输入您要操作的字符串:"<<endl;
    cin>>str;
    int len=strlen(str);
    cout<<"加密请输入1,解密请输入2,退出操作请输入0:"<<endl;
    while(cin>>n&&n)
    {
        if(n==1)
        {
            for(int i=0; i<len; i++) //字符串加密过程
                str[i]=p1[str[i]-'a'];
        }
        if(n==2)
        {
            for(int i=0; i<len; i++) //字符串解密过程
                str[i]=p2[str[i]-'a'];
        }
        cout<<str<<endl;//输出操作后字符串
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wangws_sb/article/details/83780425