1. 程式人生 > >第八週專案4--字串加密

第八週專案4--字串加密

問題及程式碼:

/* 
 *Copyright(c) 2015, 煙臺大學計算機學院 
 *All rights reserved. 
 *檔名稱:字串加密.cpp 
 *作    者:杜文文 
 *完成日期:2015年 10月 30日 
 
 *問題描述:一個文字串可用事先編制好的字元對映表進行加密。例如,設字元對映表為:

            abcdefghijklmnopqrstuvwxyz
            ngzqtcobmuhelkpdawxfyivrsj1
           則字串“lao he jiao shu ju jie gou”被加密為“enp bt umnp xby uy umt opy”。 
         設計一個程式,實現加密、解密演算法,將輸入的文字進行加密後輸出,然後進行解密並輸出。 
*/




sqString.h:

#ifndef SqString_H_INCLUDED
#define SqString_H_INCLUDED

#define MaxSize 100             //最多的字元個數
typedef struct
{   char data[MaxSize];         //定義可容納MaxSize個字元的空間
    int length;                 //標記當前實際串長
} SqString;

void StrAssign(SqString &s,char cstr[]);    //字串常量cstr賦給串s
void StrCopy(SqString &s,SqString t);   //串t複製給串s
bool StrEqual(SqString s,SqString t); //判串相等
int StrLength(SqString s);  //求串長
SqString Concat(SqString s,SqString t);  //串連線
SqString SubStr(SqString s,int i,int j); //求子串
SqString InsStr(SqString s1,int i,SqString s2); //串插入
SqString DelStr(SqString s,int i,int j) ;   //串刪去
SqString RepStr(SqString s,int i,int j,SqString t);     //串替換
void DispStr(SqString s);   //輸出串

#endif // SqString_H_INCLUDED

sqString.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<A.length; j++);
        if (j>=A.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<B.length; 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;
}


void StrAssign(SqString &s,char 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++)
            printf("%c",s.data[i]);
        printf("\n");
    }
}

int main()
{
    SqString p,q;
    StrAssign(A,"abcdefghijklmnopqrstuvwxyz");  //建立A串
    StrAssign(B,"ngzqtcobmuhelkpdawxfyivrsj");  //建立B串
    char str[MaxSize];
    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;
}


執行結果: