翻译密码(简单的 大小写英文字母后移四位,其他字符不变)C语言与Python版本

题目及分析

  • 上图片~~~
    在这里插入图片描述

c语言实现(利用ASCLL码)

// 译密码: 使用ASCLL码,转换
#include <stdio.h>

int main()
{
    
    
	// 1. 首先接收字符,我把它定义为 str,因为输出类似一个字符串
	char str;
	printf("请输入要进行转换的一段话(英文字母加字符:)\n");
	str = getchar();
	while (str != '\n')
	{
    
    
		// 2. 判断是否为 a-z,A-Z ,不是就不动
		if ((str >= 'a' && str <= 'z') || (str >= 'A' && str <= 'Z'))
		{
    
    
			// 3. 如果 > w  >W  表示要转换为 a等, 转换方式不一样。
			if ((str >= 'w' && str <= 'z') || (str >= 'W' && str <= 'Z'))
				str = str + 4 - 26;  
			else 
			// 常规 +4 转换
				str = str + 4;
		}
		printf("%c", str);

		// c语言这种直接输入一行字符串的方法,可以记住。
		str = getchar(str);
	}
	printf("\n");
	return 0;	
}

python实现(利用函数~)

  • 同样利用 ASCLL码
  • python这里给出,加密解密的函数。
def encrypt(str_c):
    result = ''
    for i in str_c:
        if i.islower():
            result += chr((ord(i) - ord('a') + 4)%26 + ord('a'))
        elif i.isupper():
            result += chr((ord(i) - ord('A') + 4)%26 + ord('A'))
        else:
            result += i
    return result

def decrypt(str_a):
    result = ''
    for i in str_a:
        if i.islower():
        	# 这里和C语言不一样, python -3%26 = 23, C语言 -3%26 = -3
            result += chr((ord(i) - ord('a') - 4)%26 + ord('a'))
        elif i.isupper():
            result += chr((ord(i) - ord('A') - 4)%26 + ord('A'))
        else:
            result += i
    return result

# print(encrypt('i" laohu you wxyzaa..'))
print(decrypt(' ABCD'))

猜你喜欢

转载自blog.csdn.net/pythonstrat/article/details/112713470