现有如下加密规则,内容遇到英文字符则往后移5位(比如a,加密后就变为f.请编写程序,实现文本加密功能,输入“Hello world!”,将加密结果输出。
时间: 2024-03-17 14:40:09 浏览: 22
好的,根据您的要求,我用 Python 编写了一个文本加密程序。以下是代码:
```python
def encrypt(text):
result = ""
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char) + 5 - 65) % 26 + 65)
else:
result += chr((ord(char) + 5 - 97) % 26 + 97)
else:
result += char
return result
text = "Hello world!"
encrypted_text = encrypt(text)
print(encrypted_text)
```
程序的逻辑很简单,就是遍历输入的文本中的每个字符,如果是英文字母则按照规则进行加密,否则直接拼接。其中,`ord()` 函数可以将字符转换成 ASCII 码,`chr()` 函数可以将 ASCII 码转换成字符。
运行程序后,输出的加密结果为:`Mjqqt btwqi!`。
相关问题
用c实现如下加密规则,内容遇到英文字符则往后移5位(比如a,加密后就变为f.请编写程序,实现文本加密功能,输入“Hello world!”,将加密结果输出。
好的,根据您的要求,我用 C 编写了一个文本加密程序。以下是代码:
```c
#include <stdio.h>
#include <string.h>
void encrypt(char* text)
{
int i, length = strlen(text);
for (i = 0; i < length; i++)
{
char c = text[i];
if (c >= 'A' && c <= 'Z')
{
c = (c - 'A' + 5) % 26 + 'A';
}
else if (c >= 'a' && c <= 'z')
{
c = (c - 'a' + 5) % 26 + 'a';
}
text[i] = c;
}
}
int main()
{
char text[] = "Hello world!";
encrypt(text);
printf("%s", text);
return 0;
}
```
程序的逻辑与 Python 版本类似,也是遍历输入的文本中的每个字符,如果是英文字母则按照规则进行加密,否则不做处理。其中,`strlen()` 函数可以获取字符串的长度。
运行程序后,输出的加密结果为:`Mjqqt btwqi!`。
3.python请编写一个加密程序。实现输入一行字符串,将其每个字母加密后 输出。提示:凯撒密码。
以下是 Python 代码实现凯撒密码加密:
```python
def caesar_cipher(text, shift):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
result += char
return result
text = input("请输入要加密的字符串:")
shift = int(input("请输入加密偏移量:"))
print("加密后的字符串为:", caesar_cipher(text, shift))
```
输入要加密的字符串和加密偏移量后,程序会输出加密后的字符串。
例如,输入字符串 "hello world" 和偏移量 3,程序会输出加密后的字符串 "khoor zruog"。
注意:凯撒密码是一种简单的加密方式,容易被破解,不适合用于真正的加密场景。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)