C语言 使用 strrev - C 反转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16946115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reversing a string with strrev - C
提问by Arlind
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.
我正在尝试使用函数 strrev() 反转字符串。我知道 strrev 返回一个指向反转字符串的指针,因此我只需使用 strrev 函数返回初始化一个与原始字符串大小相同的已分配字符串。显然,这不是正确的方法,我在该行中收到“不兼容的类型”错误。
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;
}
回答by
sr[10];
sr = strrev(s);
This doesn't even compile - arrays are not assignable. Post real code.
这甚至不能编译 - 数组不可分配。贴真实代码。
(You need to declare sras char *srfor this to actually compile at all.)
(您需要声明sr为char *sr这个在所有实际编译。)
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:
除此之外,您的问题是strrev()将字符串反转到位,因此两个字符串将始终比较相等(因为您实际上是将反转的字符串与其自身进行比较)。你需要做的是:
superfluously inefficient way: create a copy of the string,
strrev()that, thenstrcmp()the original and the copy.Somewhat more optimized approach for non-empty strings:
多余低效的方法:创建字符串的副本,
strrev()即,然后strcmp()是原始和副本。非空字符串更优化的方法:
int ispal(const char *s)
{
const char *p = s + strlen(s) - 1;
while (s < p)
if (*p-- != *s++)
return 0;
return 1;
}
回答by unxnut
OK, did some research and looks like strrevis not available in Linux (if that is your platform); check out Is the strrev() function not available in Linux?
好的,做了一些研究,看起来strrev在 Linux 中不可用(如果那是你的平台);退房strrev() 函数在 Linux 中不可用吗?
You can use the alternative implementation suggested therein or use the answer by @H2CO3.
您可以使用其中建议的替代实现或使用@H2CO3 的答案。

