• 数据结构作业-第四章-串-字符串加密


    文本串加密和解密程序

    目的:掌握串的应用算法

    内容:一个文本串可用事先给定的字母映射表进行加密。例如字母映射表为:

    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] != ''; 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;
    	}
    }
    

    运行结果

  • 相关阅读:
    决策树和随机森林
    6个开源数据科学项目
    机器学习:梯度下降
    Python中的数据结构
    方差分析介绍(结合COVID-19案例)
    html5
    归并排序
    前端与后端
    Dw3 Sublime text 3 UltraEdit XAMMPP 火狐浏览器 ISS
    ECMAScript JavaScript JScript
  • 原文地址:https://www.cnblogs.com/DTsec/p/15492395.html
Copyright © 2020-2023  润新知