检查C中的字符串是否为回文结构

Mar*_*rco -1 c string recursion dynamic palindrome

我有一个关于这个代码的问题,我正在写一个练习.我要检查字符串是否是回文.我无法更改函数的声明.当所有字母相同时(例如"aaaa"),函数只返回1,但如果我用其他回文(如"anna")充电,则函数返回0,我无法弄清楚为什么会出现这种情况.谢谢!

char* cargar (char*);
int pali (char*);

int main()
{ 
   char*texto=NULL;
   texto=cargar(texto);
   int res=pali(texto);
   if(res==1){printf("\nPalindrome");}
   else printf("\nNot palindrome");

   return 0;
}

char* cargar (char*texto)
{
   char letra;
   int i=0;
   texto=malloc(sizeof(char));
   letra=getche();
   *(texto+i)=letra;
   while(letra!='\r'){
      i++;
      texto=realloc(texto,(i+1)*sizeof(char));
      letra=getche();
      *(texto+i)=letra;}
   *(texto+i)='\0';      
   return texto;
}

int pali (char* texto)
{
   int i;
   for(i=0;*(texto+i)!='\0';i++){
   }i--;
   if(i==0||i==1){return 1;}

   if(*texto==*(texto+i)){
      return pali(++texto);
   }
   else return 0;
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 7

您确定字符串是否为回文结构的功能还没有深思熟虑.

假设你有一串s长度l.字符串中的字符布局如下:

Indices: 0    1    2    3            l-4  l-3  l-2  l-1
         +----+----+----+----+- ... -+----+----+----+----+
         |    |    |    |    |  ...  |    |    |    |    |   
         +----+----+----+----+- ... -+----+----+----+----+
Run Code Online (Sandbox Code Playgroud)

如果字符串是回文,

s[0] = s[l-1]
s[1] = s[l-2]

...
Run Code Online (Sandbox Code Playgroud)

您可以停止检查LHS的索引何时大于或等于RHS的索引.

要将其转换为代码,

int is_palindrome(char const* s)
{
   size_t len = strlen(s);
   if ( len == 0 ) // An empty string a palindrome
   {
      return 1;
   }

   size_t i = 0;
   size_t j = len-1;
   for ( ; i < j; ++i, --j )
   {
      if ( s[i] != s[j] )
      {
         // the string is not a palindrome.
         return 0;
      }
   }

   // If we don't return from inside the for loop,
   // the string is a palindrome.
   return 1;
}
Run Code Online (Sandbox Code Playgroud)