文字串加密和解密程式
阿新 • • 發佈:2018-11-19
目的:掌握串的應用演算法設計。
內容:一個文字串可用事先給定的字母對映表進行加密。例如,設字母對映表為:
a b c d e f g h i j k l m n o p q r s t u v w x y z
n g z q t c o b m u h e l k p d a w x f y i v r s j
則字串"encrypt"被加密為"tkzwsdf"。編寫一個程式exp4-4.cpp,將輸入的文字串加密後輸出,然後進行解密並輸出。
題解:字串的模擬過程。
程式碼如下:
#include <iostream> #include <cstdio> #include <cstring> using namespace std; char s1[30]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; char s2[30]= {'n','g','z','q','t','c','o','b','m','u','h','e','l','k','p','d','a','w','x','f','y','i','v','r','s','j'}; char p1[30],p2[30]; int main() { int n; char str[10000]; for(int i=0; i<26; i++) { p1[s1[i]-'a']=s2[i];//加密過程對映 p2[s2[i]-'a']=s1[i];//解密過程對映 } cout<<"請輸入您要操作的字串:"<<endl; cin>>str; int len=strlen(str); cout<<"加密請輸入1,解密請輸入2,退出操作請輸入0:"<<endl; while(cin>>n&&n) { if(n==1) { for(int i=0; i<len; i++) //字串加密過程 str[i]=p1[str[i]-'a']; } if(n==2) { for(int i=0; i<len; i++) //字串解密過程 str[i]=p2[str[i]-'a']; } cout<<str<<endl;//輸出操作後字串 } return 0; }