【问题标题】:Program that checks if an array is a palindrome检查数组是否为回文的程序
【发布时间】:2016-01-22 12:23:22
【问题描述】:

我正在尝试创建一个程序来检查给定的数组/字符串是否是回文并且它不工作。该程序仅在每个给定数组上打印“0”,即使在回文上也是如此。

int main()
{

    char string[100]= {0};
    char stringReverse[100]= {0};

    int temp = 0;
    int firstLetter = 0;
    int lastLetter = 0;

    printf("Please enter a word or a sentence: ");
    fgets(string, 100, stdin);

    strcpy(stringReverse , string); // This function copies the scanned array to a new array called "stringReverse"

    firstLetter = 0;
    lastLetter = strlen(string) - 1;    //because in array, the last cell is NULL

    // This while reverses the array and insert it to a new array called "stringReverse"
    while(firstLetter < lastLetter)
    {
        temp = stringReverse[firstLetter];
        stringReverse[firstLetter] = stringReverse[lastLetter];

        stringReverse[lastLetter] = temp;

        firstLetter++;
        lastLetter--;
    }

    printf("%s    %s", stringReverse, string);

    if ( strcmp(stringReverse , string) == 0)
    {
        printf("1");
    }
    else
    {
        printf("0");
    }
} 

【问题讨论】:

  • 这么简单的任务代码太多了。
  • 我已经发布了类似问题的答案here,您可以轻松适应您的需求

标签: c string palindrome


【解决方案1】:

假设我们实现了一个简单的乐趣来做到这一点

int check_palindrome (const char *s) {
   int i,j;
   for (i=0,j=strlen(s)-1 ; i<j ; ++i, --j) {
      if (s[i] != s[j]) return 0; // Not palindrome
   }
   return 1; //Palindrome
}

我认为这要简单得多;)

对于发布的有问题的代码: 请注意 fgets()。它在第一个 '\n' 或 EOF 处停止并保留 '\n' 字符。

所以如果你给ex给出radar,结果字符串将是"radar\n",与"\nradar"

【讨论】:

  • 没有比这更简单的方法了。这就是你所需要的。不要忘记编写一个函数来检查前导/尾随空格,你应该没问题。如果您对此有疑问,C 实际上有一个名为 isspace() 的函数,它接受一个字符(从技术上讲,它接受一个 int 但只给它一个字符)并返回一个非零值,如果它是一个空白字符,例如 \n 、\t、\v 或空格。否则返回 0。
【解决方案2】:

问题:

假设您输入字符串RACECAR 作为程序的输入,然后按回车键,这会在缓冲区流中放置一个换行符或'\n',这也会被fgets 作为字符串的一部分读取,所以你的程序最终会有效地检查 RACECAR\n 是否是回文,它不是

解决方案:

lastLetter 初始化为strlen(string) - 1 后,检查字符串中的最后一个字符(或lastLetter 索引处的字符是否为换行符(\n),如果是,则将lastLetter 减一以便您的程序检查字符串的其余部分 (RACECAR) 是否为回文。

lastLetter = strlen(string) - 1;    //because in array, the last cell is NULL

// Add these 2 lines to your code
// Checks if the last character of the string read by fgets is newline
if (string[lastLetter] == '\n')
    lastLetter--;

【讨论】:

    【解决方案3】:

    fgets 在末尾添加一个 '\n'。 因此,如果用户输入“aba”,string 包含“aba\n”。 reverseString 包含“\naba”。

    所以不匹配。

    在 fgets 之后,添加这段代码

    int l = strlen(string) - 1;
    string[l] = 0;
    

    这将在将其复制到reverseString 之前删除末尾的“\n”。

    除此之外,您可以就地执行整个程序,而无需第二个缓冲区或strcpystrlen 调用。

    【讨论】:

    • 详细信息:fgets()添加 '\n'。它像所有其他输入字符一样简单地保存它。如果用户输入只有 3 个字符:"aba",没有 键,然后关闭了 stdin,则输入将只有 'a''b''c'fgets() 确实 add 终止空字符。要安全地删除潜在的'\n',请考虑stackoverflow.com/questions/2693776/…
    【解决方案4】:

    您的代码中有几个问题:

    • 首先你忘记了最后一个右大括号}
    • 那么您忘记删除string 中的尾随\n(或者在Windows 下也可能是\r);
    • 您不需要将字符串还原为新字符串;一次检查就足够了:

    这是一个工作代码:

    #include <stdio.h>
    #include <string.h>
    int main()
    {
    
        char string[100]= {0};
    
        int temp = 0;
        int firstLetter = 0;
        int lastLetter = 0;
    
        printf("Please enter a word or a sentence: ");
        fgets(string, 100, stdin);
    
        firstLetter = 0;
        lastLetter = strlen(string) - 1;    //because in array, the last cell is NULL
        while ((string[lastLetter]=='\n')||(string[lastLetter]=='\r')) {
            lastLetter--;
        }
    
        // This while reverses the array and insert it to a new array called "stringReverse"
        temp = 1;
        while(firstLetter < lastLetter)
        {
            if (string[firstLetter] != string[lastLetter]) {
                temp = 0;
                break;
            }
    
            firstLetter++;
            lastLetter--;
        }
    
        if ( temp )
        {
            printf("1");
        }
        else
        {
            printf("0");
        }
    }
    

    【讨论】:

    • 注意:fgets(string, ...); int lastLetter = strlen(string) - 1; while ((string[lastLetter]... 是一个黑客攻击。 string 的第一个字符很容易成为'\0',然后string[-1] 是UB。考虑stackoverflow.com/q/2693776/2410359
    • @chux 是的,但这只是对原发帖者帖子的改编;我只是改变了有问题的线路。当然其他方面可以改进。
    【解决方案5】:

    你也可以用这个简单的方法来做。

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char string[10], revString[10];
        printf("Enter string for reversing it...\n");
        scanf("%s", string);
    
        int stringLength = strlen(string);
    
        for(int i = 0; string[i] != '\0'; i++, stringLength--)
        {
        revString[i] = string[stringLength - 1];
        }
    
        if(strcmp(string,  revString) == 0)
             printf("Given string is pelindrom\n");
        else
             printf("Given string is not pelindrom\n");
    }
    

    【讨论】:

    • 建议scanf("%s", tmp); 与编码gets(tmp) 差不多。都不推荐。
    【解决方案6】:
    #include<stdio.h>
    #include<string.h>`enter code here`
    void fun(char *a);
     int main () 
     {    
         
          char p[100];
          char *s=p;
          
         printf("enter the string");
         scanf("%[^\n]",s);
         fun(s);
       
         
     }
    
    void fun(char *a)
     { 
     
            
          if(*a && *a!='\n')
         {
          fun(a+1);
           
              putchar(*a);
           
          }
    }
    

    // 使用这种方法更好的时间复杂度和更容易的工作希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多