1. 程式人生 > >【資料結構 C描述】一個文字串可用事先給定的字母對映表進行加密。

【資料結構 C描述】一個文字串可用事先給定的字母對映表進行加密。

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

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” 要求:設計程式將輸入的文字串進行加密後輸出,然後進行解密並輸出。

//main.cpp
#include <iostream>
#include "SqString.h"
using namespace std;

SqString sqStr,
matchStr; //這兩個變數在main函式中作初始化 int main() { SqString encrypt(SqString p); //函式宣告 SqString Unencrypt(SqString q); //函式宣告 SqString p, q; char inputStr[MaxSize]; //存放輸入的字串 char sqChar[MaxSize] = "abcdefghijklmnopqrstuvwxyz"; //順序字串 char matchChar[MaxSize] = "ngzqtcobmuhelkpdawxfyivrsj"; //對映字串 strAssign
(sqStr, sqChar); strAssign(matchStr, matchChar); cout << "請輸入要加密的字串:" << endl; cin >> inputStr; strAssign(p, inputStr); cout << "你輸入的字串為:" << endl; DispStr(p); q = encrypt(p); cout << "加密後的字串為:" << endl; DispStr(q); p = Unencrypt(q); cout <<
"解密後的字串為:" << endl; DispStr(p); system("pause"); return 0; } SqString encrypt(SqString p){ int i = 0, j = 0; SqString q; //接收加密對應的字元 for (i = 0; i <= p.length; i++) { j = 0; while (p.data[i] != sqStr.data[j] && j < sqStr.length) { j++; //用j控制對應對映位置的字元 } if (j >= sqStr.length) q.data[i] = p.data[i]; else q.data[i] = matchStr.data[j]; //將對映的字元賦給字串q的資料 } q.length = p.length; return q; } SqString Unencrypt(SqString q){ int i = 0, j; SqString p; //接收解密對應的字元 for (i = 0; i <= q.length; i++) { j = 0; while (q.data[i] != matchStr.data[j] && j < matchStr.length) { j++; //用j控制對應解密位置的字元 } if (j >= matchStr.length) p.data[i] = q.data[i]; else p.data[i] = sqStr.data[j]; //將解密的字元賦給字串q的資料 } p.length = q.length; return p; }
//SqString.h
#include <iostream>
#define MaxSize 50
using namespace std;

typedef char ElemType;
typedef struct {
	char data[MaxSize];
	int length;
}SqString;

void strAssign(SqString &s, char cstr[]) {
	int i = 0;
	for (i = 0; cstr[i] != '\0'; i++) {
		s.data[i] = cstr[i];
	}
	s.length = i;
}

void DestroyStr(SqString &s) {

}

void DispStr(SqString s) {
	int i;
	if (s.length > 0) {
		for (i = 0; i < s.length; i++) {
			cout << s.data[i];
		}
		cout << endl;
	}
}

執行截圖
在這裡插入圖片描述