2016-08-25 158 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; 
}