首页 > 解决方案 > C Lang:使用指针和数组检查是否回文

问题描述

我一直在尝试用指针对此进行编码,我能够让第一个 for 循环工作,但我无法让另一个 for 循环使用指针工作。程序将忽略所有不是字母的字符并使用指针来代替整数以跟踪数组中的位置。我需要指针帮助来跟踪数组中的位置。

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

#define N 50

int main()
{   
    int i, j, k =0,*count;    char ch, msg[N], msg1[N];    bool flag = true;
    char *p;



    count = &k;
    // Getting user-defined input   
    printf("Enter a massage: ");
    ch = getchar();   
    while(ch != '\n' || *count == N) 
    { 

      msg[(*count)++] = ch;
      ch = getchar();   
    } // end of while loop

    // Printing user-defined input   
    printf("User-defined input: ");   
    for(p = msg; p < msg+*count; p++)       
      printf("%c",  *p);   

    printf("\nNumber of characters is %d\n", *count);       

    // Sanitiazation of the msg array (i.e., removing special characters)   
     i = 0;   
    for(j = 0; msg[j]; j++) {       
       if(isalpha(msg[j]))           
              msg1[i++] = tolower(msg[j]);   
    } // end of for loop        

   // Palindrome test    
   for(j = 0; msg1[j]; j++) {       
      if(msg1[j] != msg1[i-j-1]) {           
      flag = false;           
      continue;       
      }   
    } // end of for loop       

   // Printing final decision   
   if(flag)         
      printf("Palindrome\n");   
   else       
      printf("Not palindrome\n");    

   return 0;
} // end of main


标签: cpointers

解决方案


推荐阅读