C语言 strcmp的实现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34873209/
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
Implementation of strcmp
提问by blackFish
I tried to implement strcmp:
我试图实现strcmp:
int strCmp(char string1[], char string2[] )
{
int i=0,flag=0;
while(flag==0)
{
if (string1[i]>string2[i])
{
flag=1;
}
else if (string1[i]<string2[i])
{
flag=-1;
}
else
{
i++;
}
}
return flag;
}
but I'm stuck with the case that the user will input the same strings, because the function works with 1 and -1, but it's doesn't return 0. Can anyone help? And please without pointers!
但我坚持用户将输入相同字符串的情况,因为该函数适用于 1 和 -1,但它不返回 0。有人可以帮忙吗?并且请不要指点!
采纳答案by Daniel B.
You seem to want to avoid pointer arithmetics which is a pity since that makes the solution shorter, but your problem is just that you scan beyond the end of the strings. Adding an explicit break will work. Your program slightly modified:
您似乎想避免指针算术,这很遗憾,因为这会使解决方案更短,但您的问题只是您扫描到字符串的末尾之外。添加显式中断将起作用。您的程序略有修改:
int strCmp(char string1[], char string2[] )
{
int i = 0;
int flag = 0;
while (flag == 0)
{
if (string1[i] > string2[i])
{
flag = 1;
}
else if (string1[i] < string2[i])
{
flag = -1;
}
if (string1[i] == 'int strCmp(char string1[], char string2[] )
{
for (int i = 0; ; i++)
{
if (string1[i] != string2[i])
{
return string1[i] < string2[i] ? -1 : 1;
}
if (string1[i] == 'int strCmp(const char* s1, const char* s2)
{
while(*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
')
{
return 0;
}
}
}
')
{
break;
}
i++;
}
return flag;
}
A shorter version:
一个较短的版本:
int strCmp( const char *s1, const char *s2 )
{
const unsigned char *p1 = ( const unsigned char * )s1;
const unsigned char *p2 = ( const unsigned char * )s2;
while ( *p1 && *p1 == *p2 ) ++p1, ++p2;
return ( *p1 > *p2 ) - ( *p2 > *p1 );
}
回答by Gianluca Ghettini
Uhm.. way too complicated. Go for this one:
嗯……太复杂了。去这个:
int strcmp_refactored(const char *s1, const char *s2)
{
while (1)
{
int res = ((*s1 == 0) || (*s1 != *s2));
if (__builtin_expect((res),0))
{
break;
}
++s1;
++s2;
}
return (*s1 - *s2);
}
It returns <0, 0 or >0 as expected
它按预期返回 <0、0 或 >0
You can't do it without pointers. In C, indexing an array isusing pointers.
没有指针你就做不到。在 C 中,索引数组是使用指针。
Maybe you want to avoid using the *operator? :-)
也许您想避免使用*运算符?:-)
回答by Vlad from Moscow
First of all standard C function strcmpcompares elements of strings as having type unsigned char.
首先,标准 C 函数strcmp将字符串元素比较为具有类型unsigned char。
Secondly the parameters should be pointers to constant strings to provide the comparison also for constant strings.
其次,参数应该是指向常量字符串的指针,以便为常量字符串提供比较。
The function can be written the following way
该函数可以写成以下方式
int strcmp(const char * s1, const char * s2)
{
while (*s1 == *s2 && *s1++ | *s2++);
int i = *s1 - *s2;
return i < 0 ? -1 : i > 0 ? 1 : 0;
}
回答by Larytet
This is a 10 opcodes implementation of strcmp (GCC assumed)
这是 strcmp 的 10 个操作码实现(假设为 GCC)
-1 // <0
1 // >0
0 // ==0
You can try this implementation and compare to others https://godbolt.org/g/ZbMmYM
您可以尝试此实现并与其他实现进行比较https://godbolt.org/g/ZbMmYM
回答by Beyondo
My Implementation
我的实现
#include<stdio.h>
#include<string.h>
//using arrays , need to move the string using index
int strcmp_arry(char *src1, char *src2)
{
int i=0;
while((src1[i]!='while( flag==0 && (string1[i] != 0 | string2[i] != 0 ) )
') || (src2[i]!='##代码##'))
{
if(src1[i] > src2[i])
return 1;
if(src1[i] < src2[i])
return 1;
i++;
}
return 0;
}
//using pointers, need to move the position of the pointer
int strcmp_ptr(char *src1, char *src2)
{
int i=0;
while((*src1!='##代码##') || (*src2!='##代码##'))
{
if(*src1 > *src2)
return 1;
if(*src1 < *src2)
return 1;
src1++;
src2++;
}
return 0;
}
int main(void)
{
char amessage[] = "string";
char bmessage[] = "string1";
printf(" value is %d\n",strcmp_arry(amessage,bmessage));
printf(" value is %d\n",strcmp_ptr(amessage,bmessage));
}
return values
返回值
##代码##The last ternaryoperation is optional
最后一个三元操作是可选的
The function would still in the rules of strcmpwhen you just return *s1 - *s2.
该函数仍将在strcmp您刚刚返回时的规则中*s1 - *s2。
回答by Ashish Ahuja
回答by skyking
Your problem is that you don't detect the end of the string and therefore don't return zero if both strings ends before any difference is detected.
您的问题是您没有检测到字符串的结尾,因此如果两个字符串在检测到任何差异之前结束,则不会返回零。
You can simply fix this by checking for this in the loop condition:
您可以通过在循环条件中检查这个来简单地解决这个问题:
##代码##Note that both strings are checked because if only one is at the end the strings are not equal and the comparison inside the loop should detect that.
请注意,检查两个字符串,因为如果最后只有一个字符串,则字符串不相等,循环内的比较应该检测到这一点。
Please note that the character comparison might not yield the result that you might expect. For one it's not defined whether charis signed or unsigned so you should probably cast to unsigned charfor comparison.
请注意,字符比较可能不会产生您预期的结果。对于一个它没有定义是char有符号的还是无符号的,因此您可能应该将其转换unsigned char为进行比较。
Perhaps a cleaner solution would be to return immediately when you detect the difference, that is instead of flag = -1you return -1directly. But that's more a matter of opinion.
也许更简洁的解决方案是在您检测到差异时立即返回,而不是直接flag = -1返回-1。但这更多的是见仁见智。

