c - 使用 C 查找字符串中的所有回文

标签 c string palindrome

我正在尝试使用 C 打印字符串中的所有回文并返回总数。

我的代码返回各种非回文的子字符串并打印空白。

我的 printf 语句格式至少有一个偏差,而且,在我的数组元素比较中,它的工作方式与我的预期相反。

谁能看出我哪里出错了?

这是我的代码:

#include<stdio.h>
#include<string.h>

char x[1000];

void getString(char *n)
{
  printf("\nPlease enter your string: ");
  scanf("%s", n);
}

int findPals(char *s)
{
  int length = strlen(s);
  int numPals = 0;

  //find odd palindromes
  for(int i = 0; i < length; i++)
  {
    for(int j = 0; j + i < length && i - j >= 0; j++)
    {
      if(s[i + j] != s[i - j])
        continue;
      else
      {
        numPals++;
        printf("%.*s\n", (j - i),s + i);
      }
    }
  }

  //find even palindromes
  for(int i = 0; i < length; i++)
  {
    for(int j = 0; j + i + 1 < length && i - j >= 0; j++)
    {
      if(s[i + j + 1] != s[i - j])
        continue;
      else
      {
        numPals++;
        printf("%.*s\n", (j - i),s + i);
      }
    }
  }
  return numPals;
}

int main()
{
  char inStr[1000];
  int totalPals;

  getString(inStr);
  totalPals = findPals(inStr);
  printf("I found %d palindromes.\n", totalPals);

  return 0;
}

最佳答案

除了一切都很好之外,您的代码中只需要进行 2 个小修正(如下所示):-

1.数组检查中的Continue语句应改为break:

for(int i = 0; i < length; i++)
{
  for(int j = 0; j + i < length && i - j >= 0; j++)
  {
    if(s[i + j] != s[i - j])
      break; // continue statement has been changed to break;
    else
    {
      numPals++;
      printf(".*s\n",(2*j)+1,&s[i-j]); // The length of the string has been modified
    }
  }
}
  • printf 中的字符串长度不正确。
  • 对于奇数部分使用:

    printf(".*s\n",(2*j)+1,&s[i-j]);
    

    对于均匀部分使用:

    printf(".*s\n",(2*j)+2,&s[i-j]);
    

    关于c - 使用 C 查找字符串中的所有回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52806253/

    相关文章:

    python - 替换输入 Python 的缺失值

    javascript - 代码在控制台中有效,但在 Hackerrank 中无效

    c - 如何将文件指针 ( FILE* fp ) 转换为文件描述符 (int fd)?

    c - 指针和排序

    c - gdb 无法运行带有 "File format not recognized"的 ELF 64 位程序

    string - 如何在 Swift 中返回所有子字符串(不止一次)?

    c - 用非阻塞函数替换 system()

    javascript - 正则表达式:排除捕获可能存在或不存在的模式

    c++ - 链表中的最长回文 C++

    c - 段错误,c程序