2014-03-01 45 views
0

我需要通過the_message_array循環,然後打印字母表中的字母,當它相當於the_alphabet_array中的數字時。 The_alphabet_array的元素與字母匹配,即the_alphabet_array [0]匹配a,the_alphabet_array [1]匹配b,依此類推。我不能使用ascii,這些字母指向the_alphabet_array中的特定數字。如果還有另一種更簡單的方法來做到這一點,而不是通過26條if語句,我會非常感謝幫助。 這裏是字母陣列:C - 使用指針來創建更多高效的循環遍歷字母表

2, 0, 15, 14, 24, 6, 19, 9, 25, 13, 7, 5, 21, 10, 12, 11, 4, 22, 23, 20, 17, 8, 18, 3, 1, 16 

這裏是消息數組:

15 ,12,10,19,22,2,20,17,5 ,2,20,25 ,12 ,10 ,23 

所以 'A' 點到2字母表陣列中, 'B' 指向0,等。當2發生在消息數組中,打印出'a'。

int the_letter_char[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'}; 
int message_equals_cipher = 0; 

    for(message_equals_cipher; message_equals_cipher < 15; message_equals_cipher++){ 
      if(the_message_array[message_equals_cipher] == the_alphabet_array[0]){ 
        printf("%c", the_letter_char[0]); 
      } 
      if(the_message_array[message_equals_cipher] == the_alphabet_array[1]){ 
        printf("%c", the_letter_char[1]); 
      } 
      if(the_message_array[message_equals_cipher] == the_alphabet_array[2]){ 
        printf("%c", the_letter_char[2]); 
      } 
    } 

回答

2

可能是做的最好的事情是簡單地,如果字符的ASCII值是正確的範圍內,這樣的:

char c = the_message_array[message_equals_cipher]; 
if (c > 63 && c < 91) || (c > 96 && c < 123) { 
    printf("%c", c); 
} 
+0

對不起,我沒有具體說明,但我不能使用ASCII值。我編輯了我的問題和代碼以獲取更多細節。 – lchristina26

0

最直接的答案是內部使用一個循環你的循環。

int message_equals_cipher = 0; 
for (message_equals_cipher; message_equals_cipher < 15; message_equals_cipher++) 
    { 
    for (int i = 0; i < sizeof(the_alphabet_array) ; i += 1) 
     { 
     if (the_message_array[message_equals_cipher] == the_alphabet_array[i]) 
      { 
      printf("%c", the_letter_char[i]); 
      } 
     } 
    } 

注意這意味着遍歷在the_message_array每個字母整個the_alphabet_array。它並不是最有效的算法,但它等同於並優於在代碼中手動輸出每個條件。 (這是O(N * M); https://en.wikipedia.org/wiki/Time_complexity

對於更快的算法來檢查一個字符是在一定範圍內,如果你只需要處理ASCII字符,使用數字代碼中看到jwosty的答案的每個角色。 (他還識別大寫和小寫字母)

請注意,C在處理整數與字符時不小心。有時你可以利用這個優勢,但有些時候你需要特別小心,不要無意中混淆它們。

1

你需要另一個數組如new_alphabet:

char new_alphabet[26]; 
for(i = 0; i < 26; i++){ 
    new_alphabet[ the_alphabet_array[i] ] = the_letter_char[i]; 
} 

然後:

for(message_equals_cipher; message_equals_cipher < 15; message_equals_cipher++){ 
    printf("%c", new_alphabet[ the_message_array[message_equals_cipher] ]); 
}