带倒车一个strrev字符串 - Ç [英] Reversing a string with strrev - C

查看:125
本文介绍了带倒车一个strrev字符串 - Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图扭转使用功能strrev一个字符串()。我知道strrev返回一个指向字符串逆转,所以我只是初始化一个已分配的字符串,同样大小的原与strrev函数返回。显然,这不是做了正确的方式,我在该行得到一个不兼容的类型错误。

这里的code:

  INT ispalindrome(INT N)
{
   个char [10],SR [10];   itoa(N,S,10);   的printf(%S,S);   SR = strrev(多个);   的printf(\\ nReverse:%S,SR);   如果(STRCMP(S,SR)== 0)
       返回1;   其他
       返回0;}


解决方案

  SR [10];
SR = strrev(多个);

这甚至不编译 - 数组是不可转让。 发表现实code。

(需要声明 SR 的char * SR 此实际编译的。)


除此之外,你的问题是, strrev()在当前位置倒转字符串,所以这两个字符串总是等于(因为你是比较有效的逆转字符串本身)。你有什么要做的是:


  • 多余地低效的方式:创建字符串的副本, strrev()这一点,那么的strcmp()原件及复印件。


  • 有关非空字符串较为优化的方式:



  INT ispal(为const char * S)
{
    为const char * P = S +的strlen(S) - 1;
    而(S< P)
        如果(* P--!= * S ++)
            返回0;    返回1;
}

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;

}

解决方案

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;
}

这篇关于带倒车一个strrev字符串 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆