密码加密-向后偏移

2023-12-23 06:34:40

一.代码部分

#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,防止后越界

文章来源:https://blog.csdn.net/lanssssss/article/details/135138934
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。