Reversing a string with strrev - C

≡放荡痞女 提交于 2020-01-14 02:53:07

问题


I'm trying to reverse a string using the function strrev(). I know that strrev returns a pointer to the reversed string so I simply initialize an already allocated string with same size as the original one with the strrev function return. Obviously this isn't the correct way to do it and I get an "incompatible types" error in that line.

Here's the code:

int ispalindrome(int n)
{
   char s[10], sr[10];

   itoa(n, s, 10);

   printf("%s", s);

   sr = strrev(s);

   printf("\nReverse: %s", sr);

   if(strcmp(s, sr) == 0)
       return 1;

   else
       return 0;

}

回答1:


sr[10];
sr = strrev(s);

This doesn't even compile - arrays are not assignable. Post real code.

(You need to declare sr as char *sr for this to actually compile at all.)


Apart from that, your issue is that strrev() reverses the string in place, so the two strings will always compare equal (since you're effectively comparing the reversed string with itself). What you have to do is:

  • superfluously inefficient way: create a copy of the string, strrev() that, then strcmp() the original and the copy.

  • Somewhat more optimized approach for non-empty strings:


int ispal(const char *s)
{
    const char *p = s + strlen(s) - 1;
    while (s < p)
        if (*p-- != *s++)
            return 0;

    return 1;
}



回答2:


OK, did some research and looks like strrev is not available in Linux (if that is your platform); check out Is the strrev() function not available in Linux?

You can use the alternative implementation suggested therein or use the answer by @H2CO3.



来源:https://stackoverflow.com/questions/16946115/reversing-a-string-with-strrev-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!