编写一个数据加密程序,从键盘输入一个由字母,数字,空格组成的字符串,输出其对应的密文。加密规则是:将字符串中每个字符的ascii码值加100,C语言
时间: 2023-06-11 07:09:37 浏览: 82
以下是一个简单的实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char input[MAX_LEN], encrypted[MAX_LEN];
int i;
printf("请输入要加密的字符串:\n");
fgets(input, MAX_LEN, stdin);
for (i = 0; i < strlen(input); i++) {
encrypted[i] = input[i] + 100;
}
printf("加密后的字符串为:\n%s", encrypted);
return 0;
}
```
代码中使用 `fgets` 函数读取输入字符串,遍历字符串中的每个字符,将其 ASCII 码值加上 100,得到密文。最后使用 `printf` 函数输出密文字符串。需要注意,密文字符串的长度可能会超过原字符串的长度,因此需要定义足够长的数组来存储密文字符串。
相关问题
用python 自己编写程序,测试字符串相应方法,及正则表达式,完成凯撒加密程序设计
好的,我可以帮你回答这个问题。下面是一个简单的凯撒加密程序的设计,使用Python语言实现。
```python
def caesar_encrypt(plaintext, shift):
"""
凯撒加密函数
plaintext: 明文
shift: 加密偏移量
"""
ciphertext = ""
for char in plaintext:
if char.isalpha():
# 对于字母字符进行加密
if char.islower():
ciphertext += chr((ord(char) - 97 + shift) % 26 + 97)
else:
ciphertext += chr((ord(char) - 65 + shift) % 26 + 65)
else:
# 对于非字母字符原样输出
ciphertext += char
return ciphertext
```
上面这个函数接受两个参数,明文和加密偏移量,返回加密后的密文。它的实现方法是对明文中的每个字符进行加密,对于字母字符应用凯撒加密算法,对于非字母字符原样输出。这里假设明文只包含英文字母和空格符。
下面是一个简单的测试例子:
```python
plaintext = "hello world"
shift = 3
ciphertext = caesar_encrypt(plaintext, shift)
print("明文:", plaintext)
print("密文:", ciphertext)
```
输出结果为:
```
明文: hello world
密文: khoor zruog
```
你还可以使用Python的正则表达式模块re来进行字符串的匹配和替换操作。例如,要将一个字符串中的所有数字替换成星号,可以使用如下代码:
```python
import re
s = "abc123def456"
s = re.sub(r"\d", "*", s)
print(s)
```
输出结果为:
```
abc***def***
```
上面的代码中,re.sub函数使用正则表达式r"\d"匹配字符串中的所有数字,然后将其替换成星号。
用c++编程:加密程序:由键盘输入明文,通过加密程序转换成密文并输出到屏幕上。算法:明文中的字母转换成其后的第4个字母,例如:A变成E(a变成e),Z变成D,非字母字符不变;同时将密文每两个字符之间插入一个空格。例如:China转换成密文为Glmre。要求:在函数change中完成字母转换,在函数insert中完成增加空格,用指针传递参数。
我可以回答这个问题。以下是加密程序的代码:
#include <stdio.h>
#include <ctype.h>
void change(char *s) {
while (*s) {
if (isalpha(*s)) {
*s = (*s - 'A' + 4) % 26 + 'A';
}
s++;
}
}
void insert(char *s) {
while (*s) {
putchar(*s);
if (*(s+1)) {
putchar(' ');
}
s++;
}
}
int main() {
char str[100];
printf("请输入明文:");
fgets(str, 100, stdin);
change(str);
insert(str);
return 0;
}
这个程序中,change函数用来将明文中的字母转换成密文,insert函数用来在密文中插入空格。在主函数中,先从键盘输入明文,然后调用change和insert函数进行加密和输出。指针被用来传递字符串参数。