编与一个程序,要求出入一个字符串,并输入一个整数作为凯撒加密算法的秘钥,输出该字符串加密后的结果。
时间: 2023-11-27 12:50:15 浏览: 55
以下是 Python 语言实现的示例代码:
```python
def caesar_cipher(text, key):
"""
凯撒加密算法实现函数
"""
result = ""
for char in text:
if char.isalpha():
# 处理字母
shifted = ord(char) + key
if char.isupper():
if shifted > ord('Z'):
shifted -= 26
elif shifted < ord('A'):
shifted += 26
else:
if shifted > ord('z'):
shifted -= 26
elif shifted < ord('a'):
shifted += 26
result += chr(shifted)
else:
# 非字母字符直接拼接
result += char
return result
# 示例
text = input("请输入要加密的字符串:")
key = int(input("请输入秘钥(整数):"))
encrypted_text = caesar_cipher(text, key)
print("加密后的字符串为:", encrypted_text)
```
使用方法:
1. 运行程序
2. 输入要加密的字符串
3. 输入秘钥,秘钥为一个整数
4. 程序输出加密后的字符串
注意:
- 该实现默认只能处理英文字母,对于其他字符会直接拼接到结果中
- 加密后的字符串中,大写字母仍为大写字母,小写字母仍为小写字母。如果需要转换为统一大小写,可以在处理完后添加 `.lower()` 或 `.upper()` 方法