【数据结构 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;
	}
}

运行截图
在这里插入图片描述

  • 13
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值