2016-08-25 122 views
-1

編寫一個函數來檢查字符串是否是迴文。必須使用遞歸函數並忽略空格。 我已經完成了第一部分,但仍未弄清楚如何忽略空間。 以下代碼是我已經嘗試過的。C:檢查字符串是否爲Palindrome

#include "stdafx.h" 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h>// this is used for strlen 
#include <ctype.h>// this is used for isalnum 

int checking_palindrome(char *string,int length); 
int main() 
{ 
    int result,length; 
    char string[] = "a ma ma"; 
    length = strlen(string); 
    result= checking_palindrome(string,length); 
    if (result == 1) 
     printf("The array is palindrome.\n"); 
    else 
     printf("The array is not palindrome.\n"); 
    system("pause"); 
    return 0; 
} 
int checking_palindrome(char *string, int length) 
{ 
    if (length <= 0) 
     return 1; 
    else if (string[0] == string[length-1]) 
     return checking_palindrome(&string[0], length - 2); 
    else 
     return 0; 
} 
+1

爲什麼您使用'&string [0]'而不是'&string [1]'或者'string + 1'作爲'checking_palindrome()'的第一個參數? – MikeCAT

+2

瞭解如何使用調試器,以及如何在監控變量及其值的同時逐行執行代碼。這會很快幫助你。對於任何想要更嚴肅地進行編程的人來說,這也是一項關鍵技能,即使對於業餘愛好程序員也是如此。 –

+0

@MikeCAT其實,那是我的錯。我的原始代碼是&string [1]。 –

回答

2

要忽略空間,請編寫代碼以忽略空間。

int checking_palindrome(char *string, int length) 
{ 
    if (length <= 0) 
     return 1; 
    else if (string[0] == ' ') 
     /* ignore space at the head of the string */ 
     return checking_palindrome(&string[1], length - 1); 
    else if (string[length-1] == ' ') 
     /* ignore space at the tail of the string */ 
     return checking_palindrome(&string[0], length - 1); 
    else if (string[0] == string[length-1]) 
     /* Respecting original code: &string[0] is used instead of &string[1] for some reason */ 
     return checking_palindrome(&string[0], length - 2); 
    else 
     return 0; 
} 
+1

尊重原始代碼是不明智的,因爲這是原代碼中的缺陷之一。我有一種感覺,使用'amama'測試OP,所以將長度減少2就得到'ama'。但代碼仍然是錯誤的。另外,第一個「if」可以是「if(length <= 1)」。 – user3386109

+1

另外,如果部分迴文更有可能比不匹配的空白,那麼在長度檢查之後立即進行等式檢查將是勝利。 – rici

0

從我的tute獲得建議後,最好從數組中刪除空格並將值放入新數組中。然後,傳遞新的數組來運行。

#include "stdafx.h"//Visual Studio 2015 
#include <stdio.h> 
#include <stdlib.h>// using for command system("pause") ; 
#include <string.h> 


int checking_palindrome(char *string, int length); 
int main() 
{ 
    int i,j,result, length; 
    char string[] = "a ma ma",newstring[50]; 

    length = strlen(string); 
    for(i=0,j=0;i<length;i++) 
     if (string[i] != ' ') 
     { 
      newstring[j] = string[i]; 
      j++; 
     } 
    newstring[j] = '\0'; 
    length = strlen(newstring); 

    result = checking_palindrome(newstring, length); 
    if (result == 1) 
     printf("The array is palindrome.\n"); 
    else 
     printf("The array is not palindrome.\n"); 
    system("pause"); 
    return 0; 
} 
int checking_palindrome(char *string, int length) 
{ 
    if (length <= 0) 
     return 1; 
    else if (string[0] == string[length - 1]) 
     return checking_palindrome(&string[1], length - 2); 
    else 
     return 0; 
}