密码加密-向后偏移

一.代码部分

#include<stdio.h>
#define MAXLINE 80
#define M 26
int main() {
	int i, offset;
	char str[MAXLINE];
	printf("enter a string:");
	i = 0;
	while ((str[i] = getchar()) != '\n') {
		i++;
	}
	str[i] = '\0';
	printf("Enter offset:");
	scanf_s("%d", &offset);
	if (offset >=M) {//当offset大于等于26时,移位效果相当于取其余数
		offset = offset % M;
	}
	for (i = 0; str[i] != '\0'; i++) {
		if (str[i ]>= 'A' && str[i] <= 'Z') //分大小写
		{
			if ((str[i] - 'A' + offset) < M) //从0开始索引,A对应0,以此类推
			{
				str[i] += offset;
			}
			else//如果向后越界
			{
				str[i] = str[i] - (M - offset);
			}
		}
		else if (str[i] >= 'a' && str[i] <= 'z') {
			if ((str[i] - 'a' + offset) < M)
			{
				str[i] += offset;
			}
			else
			{
				str[i] = str[i] - (M - offset);
			}
		}
	}
	printf("After being encrypted:");
	for (i = 0; str[i] != '\0'; i++) {
		putchar(str[i]);
	}
	printf("\n");
		return 0; 
}

二.核心代码分析

for (i = 0; str[i] != '\0'; i++) {
		if (str[i ]>= 'A' && str[i] <= 'Z') //分大小写
		{
			if ((str[i] - 'A' + offset) < M) //从0开始索引,A对应0,以此类推
			{
				str[i] += offset;
			}
			else//如果向后越界
			{
				str[i] = str[i] - (M - offset);
			}
		}
		else if (str[i] >= 'a' && str[i] <= 'z') {
			if ((str[i] - 'a' + offset) < M)
			{
				str[i] += offset;
			}
			else
			{
				str[i] = str[i] - (M - offset);
			}
		}
	}

if (str[i ]>= 'A' && str[i] <= 'Z') { ... } else if (str[i] >= 'a' && str[i] <= 'z') { ... }检查字符大小写区分开

if ((str[i] - 'A' + offset) < M) { str[i] += offset; } else { str[i] = str[i] - (M - offset); }从0开始索引并加上偏移量,并检查是否小于26,防止后越界

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值