我对strcmp()感到困惑,或者更确切地说,它是如何被标准定义的。考虑比较两个字符串,其中一个字符串包含ASCI-7范围之外的字符(0-127)。
C标准定义:
int strcmp(const char *s1,const char *s2);
strcmp函数将s1指向的字符串与s2指向的字符串进行比较。
strcmp函数相应地返回大于、等于或小于零的整数,因为s1指向的字符串大于、等于或小于s2所指向的字符串。
参数为char *.不是unsigned char *.没有所谓的“比较应该作为unsigned”的概念。
但是,我检查的所有标准库都认为“高”字符就是这个字符,比ASCII-7字符的值更高。
我知道这是有用的,也是人们期望的行为。我不想说现有的实现是错误的或什么的。我只想知道,标准规格中的哪一部分我错过了
int strcmp_default( const char * s1, const char * s2 )
{
while ( ( *s1 ) && ( *s1 == *s2 ) )
{
++s1;
++s2;
}
return ( *s1 - *s2 );
}
int strcmp_unsigned( const char * s1, const char *s2 )
{
unsigned char * p1 = (unsigned char *)s1;
unsigned char * p2 = (unsigned char *)s2;
while ( ( *p1 ) && ( *p1 == *p2 ) )
{
++p1;
++p2;
}
return ( *p1 - *p2 );
}
#include <stdio.h>
#include <string.h>
int main()
{
char x1[] = "abc";
char x2[] = "abü";
printf( "%d\n", strcmp_default( x1, x2 ) );
printf( "%d\n", strcmp_unsigned( x1, x2 ) );
printf( "%d\n", strcmp( x1, x2 ) );
return 0;
}产出如下:
103
-153
-153发布于 2009-08-31 10:46:46
7.21.4/1 (C99),重点是我的:
比较函数memcmp、strcmp和strncmp返回的非零值的符号由所比较对象中不同的第一对字符(都解释为无符号字符)的值之间的差异符号决定。
在C90中也有类似的地方。
注意,strcoll()可能比strcmp()更适应,特别是在基本字符集之外有字符的情况下。
https://stackoverflow.com/questions/1356741
复制相似问题