- #include <iostream>
- using namespace std;
- #define MaxSize 50
-
- typedef char ElemType;
- typedef struct {
- char data[MaxSize];
- int length;
- } SqString;
- SqString sqStr, matchStr;
- void create(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 show(SqString s) {
- int i;
- if (s.length > 0) {
- for (i = 0; i < s.length; i++) {
- cout << s.data[i];
- }
- cout << endl;
- }
- }
- SqString jiami(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 jiemi(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;
- }
- int main() {
- SqString jiami(SqString p); //函数声明
- SqString jiemi(SqString q); //函数声明
- SqString p, q;
- char inputStr[MaxSize]; //存放输入的字符串
- char sqChar[MaxSize] = "abcdefghijklmnopqrstuvwxyz"; //顺序字符串
- char matchChar[MaxSize] = "ngzqtcobmuhelkpdawxfyivrsj"; //映射字符串
- create(sqStr, sqChar);
- create(matchStr, matchChar);
- cout << "输入字符串:" << endl;
- cin >> inputStr;
- create(p, inputStr);
- cout << "原文串:" << endl;
- show(p);
- q = jiami(p);
- cout << "加密串:" << endl;
- show(q);
- p = jiemi(q);
- cout << "解密串:" << endl;
- show(p);
-
- system("pause");
- return 0;
- }
-
1.1 实验目的
掌握串的应用算法设计。
1.2实验内容
一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:
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,将输入的文本串加密后输出,然后进行解密并输出。