Python3
# 凯撒密码
def CaesarCode(Str, key):
s = []
#将字符串转为ascii数组
for i in range(len(Str)):
s.append(ord(Str[i]))
for i in range(len(s)): #遍历字符串
if s[i]>=65 and s[i]<=90: #大写
if s[i]+key>90:
s[i] -= 26
s[i] += key
elif s[i]>=97 and s[i]<=122: #小写
if s[i]+key>122:
s[i] -= 26
s[i] += key
code = ''
for j in range(len(s)):
code += chr(s[j])
print(code)
if __name__ == '__main__':
s = input("Please Input Your String:")
for i in range(26):
CaesarCode(s, i)
运行截图:
C++
#include<bits/stdc++.h>
using namespace std;
void Caesar(char s[], int key){
char str[100];
strcpy(str, s);
for(int i=0; str[i]!='\0'; i++){ // 遍历字符串str的每一个字符
if(str[i]>='a' && str[i]<='z'){ // 小写字母
if(str[i]+key > 'z') str[i] -= (26-key);
else str[i] += key;
}
else if(str[i]>='A' && str[i]<='Z'){ // 大写字母
str[i] += key;
if(str[i]>'Z') str[i]-=26;
}
}
printf("key = %d , code = %s \n", key, str);
}
int main(){
char s[100];
printf("Input String:\n ");
gets(s);
for(int i=1; i<26; i++){
Caesar(s, i);
}
}
运行截图:
写的时候犯了很傻逼的错误,请教了大佬轻松解决了
hsyyyds!!