2017-09-19 36 views
1

嗨我在嘗試使用指針進行加密和解密字符串時被卡住了。我需要將字母加1。 例如:你好會是Ifmmp。而且我還需要消除其他字符,如$%^^。所以當字符串是'z'+1會給我'a' 這是我的代碼。使用指針移位+1來加密和解密字符串

char *cipher(char *s) { 
    int i =0; 
    int shift = 1; 

    while(*(s+i)!= '\0') { 
     if (*(s+i)) { 
      *(s+i)+= (shift); 
     } 
     i++; 
    } 
} 

char *decipher(char *s) { 
    int i =0; 
    int shift = -1; 

    while(*(s+i)!= '\0') { 
     if (*(s+i) +shift) { 
      *(s+i)+= (shift); 
     } 
     i++; 
    } 
} 

我的電流輸出爲: 到加密:abcxyz - > bcdyz { 破譯:bcdyz { - > abcxyz

感謝

+3

我敢肯定,'如果(*(S + I)+ SHIFT> = 65 &&(*(S + I)+ =移<= 90))'不會做你想要什麼。注意'*(s + i)+ = ...'。 – mch

+0

謝謝,解決了這個問題。你有什麼想法,我可以消除其他字符,如!@#$? @mch – skylight

+0

看看http://man7.org/linux/man-pages/man3/isalpha.3.html – mch

回答

0

First of all,改而到for循環,如果你增加itearator在for循環和你的條件最好的可讀的代碼是for循環

Second,你需要添加condtion- If信是'z'分配「一」 else做同樣的事情

第三,如果你想avoide你需要添加另一個字母條件:

if((*s+i)<'a' || (*s+i)>'z'){ 
    do what you want 
} else { 
    avoide 
} /// it will work if you use character encoding that the alphebet is by order and continuous 

我在chipher功能添加與修改代碼,你將在同一添加到下一個功能

char *cipher(char *s){ 
int shift = 1; 
for(int i=0; *(s+i)!= '\0'; i++){ 
    if (*(s+i)){ 
    //i add that condtion for 'z' you need to add the same condition   to the next function 
    if(*(s+i)=='z'){ 
    *(s+i)='a'; 
    }else{ 
    *(s+i)+= (shift); 
    } 
    } 
} 
} 

char *decipher(char *s){ 
    int shift = -1; 
    for(int i=0 ;*(s+i)!= '\0'; i++){ 
    if (*(s+i) +shift){ 
     *(s+i)+= (shift); 
    } 
    } 
} 
+0

謝謝!感謝你的幫助! – skylight

0

我需要通過+1

字母表轉移0

僅移位字符a-z。所以代碼必須檢測這些

char *shift_AZ(char *s, int shift) { 
    // Bring shift into 0-25 range 
    shift %= 26; 
    if (shift < 0) shift += 26; 

    // loop until at end of string 
    // while(*(s+i)!= '\0') { 
    while(*s) { 
    // Assuming ASCII, detect select characters 
    if ((*s >= 'a') && (*s <= 'z')) { 
     // Do the shift, wrap around via %26 
     *s = (*s - 'a' + shift)%26 + 'a'; 
    } 
    s++; // next chraracter 
    } 

    char *cipher(char *s) { 
    return shift_AZ(s, 1); 
    } 

    char *decipher(char *s) { 
    return shift_AZ(s, -1); 
    }