1. 程式人生 > >文字串加密和解密程式程式碼

文字串加密和解密程式程式碼

題目描述:

一個文字串可用事先給定的字母對映表進行加密。例如,設字母對映表為:

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<string.h>
#include<stdio.h>
#include<algorithm>
typedef long long ll;
char arr[100]= {"abcdefghijklmnopqrstuvwxyz"};
char brr[100]= {"nbzqtcobmuhelkpdawxfyivrsj"};
int main()
{
    char crr[100],drr[100],err[100];
    int i,j;
    gets(crr);
    printf("原文字為:\n");
    puts(crr);
    for(i=0; i<strlen(crr); i++)
    {
        for(j=0; j<strlen(arr); j++)
        {
            if(crr[i]==arr[j])
                drr[i]=brr[j];
        }
    }
    drr[i]='\0';
    printf("加密文字為:\n");
    puts(drr);
    for(i=0; i<strlen(drr); i++)
    {
        for(j=0; j<strlen(brr); j++)
        {
            if(drr[i]==brr[j])
                err[i]=arr[j];
        }
    }
    err[i]='\0';
    printf("解密文字為:\n");
    puts(err);
    return 0;
}
 

利用字串的輸入、查詢、輸出等操作