2012-02-29 62 views
1

正在處理一個小程序,該程序將從用戶處取得一個字符串並查看它是否是迴文。 (一個詞組以相同的方式向後拼寫,如「從不奇怪或甚至」)我已經構建了從字符串中刪除空格和任何非字母字符的函數,然後也創建了字符串的副本。 (所有這三個函數都經過了充分的測試,沒有問題。)現在我正在研究一個函數,它需要比較兩個字符串以查看字符串是否以相同的方式向前和向後拼寫。布爾函數將無法正確地比較數組

函數應該通過向前循環主字符串並向後複製並比較每個元素來決定它是否是迴文。然而我一直得到一個錯誤的答案,我做錯了什麼?

_Bool isPalindrome(char str[], char copy[]) 
{ 
    int i = 0; 
    int count = 0, j = 0; 

    // loop through the main string to find the number of elements 
    while(str[j] != '\0') 
    { 
    count++; 
    j++; 
    } 

    //loop through the main string until the null character. 
    while(str[i] != '\0') 
    { 
    // to loop through the copy backwards, 
    // use the size of the first and subtract i 
    size = count - i; 
    if(str[i] != copy[size]) 
     return FALSE; 
    i++; 
    } 

    return TRUE; 
} 
+0

試運行調試器?你的第一個循環也相當於'strlen'。 – cnicutar 2012-02-29 16:55:49

+0

用筆和紙以及兩個長度爲一個字符的輸入字符串運行您的代碼。走着瞧吧。 – Mat 2012-02-29 16:58:03

回答

0

它應該是:

size = count - i - 1; 
+0

嘿它工作,謝謝! – Ryan 2012-02-29 17:22:00