帮我写一个凯撒算法的伪代码
时间: 2023-06-07 07:10:27 浏览: 42
当然,下面是凯撒算法的伪代码:
```
function CaesarCipher(plainText, shift) {
let cipherText = ""
for (let i = 0; i < plainText.length; i++) {
let char = plainText[i]
if (char.match(/[a-z]/i)) {
let code = plainText.charCodeAt(i)
if (code >= 65 && code <= 90) {
char = String.fromCharCode(((code - 65 + shift) % 26) + 65)
}
else if (code >= 97 && code <= 122) {
char = String.fromCharCode(((code - 97 + shift) % 26) + 97)
}
}
cipherText += char
}
return cipherText
}
```
希望可以帮到你!
相关问题
帮我用c语言写一个凯撒加密
好的,我可以回答这个问题。以下是一个简单的凯撒加密的 C 语言代码示例:
```c
#include <stdio.h>
#include <string.h>
void caesar_encrypt(char *str, int shift) {
int len = strlen(str);
for (int i = ; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = 'a' + (str[i] - 'a' + shift) % 26;
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = 'A' + (str[i] - 'A' + shift) % 26;
}
}
}
int main() {
char str[100];
int shift;
printf("请输入要加密的字符串:");
scanf("%s", str);
printf("请输入加密偏移量:");
scanf("%d", &shift);
caesar_encrypt(str, shift);
printf("加密后的字符串为:%s\n", str);
return ;
}
```
这个程序会让用户输入一个字符串和一个加密偏移量,然后对字符串进行凯撒加密,并输出加密后的结果。
帮我写可视化凯撒密码代码
以下是一个简单的可视化凯撒密码的C语言代码,它可以将输入的明文进行加密或解密:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
void encrypt(char *str, int key) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = (str[i] - 'a' + key) % 26 + 'a';
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = (str[i] - 'A' + key) % 26 + 'A';
}
}
}
void decrypt(char *str, int key) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = (str[i] - 'a' - key + 26) % 26 + 'a';
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = (str[i] - 'A' - key + 26) % 26 + 'A';
}
}
}
int main() {
char str[MAX_LEN];
int key;
int choice;
printf("请输入明文:");
fgets(str, MAX_LEN, stdin);
printf("请输入密钥:");
scanf("%d", &key);
printf("请选择操作:\n");
printf("1. 加密\n");
printf("2. 解密\n");
scanf("%d", &choice);
switch (choice) {
case 1:
encrypt(str, key);
printf("加密后的密文为:%s\n", str);
break;
case 2:
decrypt(str, key);
printf("解密后的明文为:%s\n", str);
break;
default:
printf("无效的选择!\n");
break;
}
return 0;
}
```
该代码中,encrypt函数和decrypt函数分别用于加密和解密字符串,key表示密钥,choice表示用户选择的操作。用户可以输入明文和密钥,然后选择加密或解密操作,程序会输出相应的结果。