串
文本串加密和解密程序
目的:掌握串的應用算法
內容:一個文本串可用事先給定的字母映射表進行加密。例如字母映射表為:
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,將輸入的文本串加密后輸出,然后進行解密並輸出。
exp4-4.cpp
main:
#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;
}
}
運行結果