c - 回文 - 删除 goto

标签 c palindrome

美好的一天! 我们的老师要求我们确定一个单词或一系列数字是否是回文或不使用堆栈。我已经做完了。但是我想多练习,所以现在我正在尝试通过删除空格和其他不相关的字符来确定一个句子是否是回文(注意:不再是我的作业的一部分)我的代码已经在工作(希望如此)但我发现它凌乱。所以我想改进它。我想删除 goto 功能,因为我的老师建议我不要使用它。我怎样才能不使用 goto 函数退出 if 语句?先感谢您。还有其他方法可以检查一个句子是否是回文,因为我的代码是用蛮力方法完成的。我的代码如下:注意(我没有在此处包含/粘贴结构以及弹出和推送功能)

int main(){
   char word[11];
   char temp[11];
   char value;
   int i=0, x=0, n=0, length=0; 
   Stack*head = NULL;
   printf("Please type the word: ");
   gets(word);
   length = strlen(word);
   while(i<length){
       if(isspace(word[i]) || !isalpha(word[i]))  {
           if(isdigit(word[i])) goto NEXT;  // i used the goto function here
           i++; 
           continue;
       }
       NEXT:
       temp[n]=word[i];
       push(&head, word[i]);
       i++;
       n++;
   }
   temp[n]='\0';
   while(x<n){
       value = pop(&head);         
       if (value==temp[x]){ 
           x++; 
           continue;
       }
       break;
   }    
   if(x==n) printf("Yehey! It is a palindrome.");
   else printf("Sorry, It is not a palindrome.");
   getch();
}

根据您的建议。这是我改进后的代码:

int main(){
   char word[11];
   char temp[11];
   int i=0, n=0; 
   int flag = 1;
   Stack*head = NULL;
   printf("Please type the word: ");
   fgets(word, 11, stdin);
   for(i = 0; word[i]!='\0' ; i++){
       if(isalnum(word[i])) {
           temp[n]=word[i];
           push(&head, word[i]);
           n++;
       }
   }
   temp[n]='\0';
   for(i=0; temp[i]!='\0'; i++){
       if (pop(&head)!=temp[i]){ 
          flag = 0;
          break;
       }
   }    
   if (flag==1) printf("Yehey! It is a palindrome.");
   else printf("Sorry, It is not a palindrome.");
   getch();
}

最佳答案

您可以进行的最简单的更改如下:

   ...
   if(isspace(word[i]) || !isalpha(word[i]))  {
       if(!isdigit(word[i])) {
           i++; 
           continue;
        }
   }
   temp[n]=word[i];
   ...

您还可以做一些其他事情来整理代码(例如,合并 if 语句,摆脱 isspace since !isalpha 涵盖了等等)。

关于c - 回文 - 删除 goto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4429033/

相关文章:

c - 如何在 C 中使用双重结构的动态分配(malloc)?

c - 循环不起作用

java - 从字符串数组列表中查找最短回文的有效方法

java - 我发现我的输出有一个小问题!谁能说出我的代码发生了什么?

c - 如何在不选择的情况下检查非阻塞套接字超时

c++ - atoi 似乎不能正常工作

c++回文程序使用数组

javascript - 如何创建回文检查器?

c - 简单的程序结果为 "Stack Smashing"

algorithm - 如何检测回文的第​​一次出现