c++字符串的比较

2025-06-27 23:12:31
推荐回答(2个)
回答1:

#include
#include

char string1[] = "The quick brown dog jumps over the lazy fox";
char string2[] = "The QUICK brown dog jumps over the lazy fox";

void main( void )
{
char tmp[20];
int result;
/* Case sensitive */
printf( "Compare strings:\n\t%s\n\t%s\n\n", string1, string2 );
result = strcmp( string1, string2 );
if( result > 0 )
strcpy( tmp, "greater than" );
else if( result < 0 )
strcpy( tmp, "less than" );
else
strcpy( tmp, "equal to" );
printf( "\tstrcmp: String 1 is %s string 2\n", tmp );
/* Case insensitive */
result = _stricmp( string1, string2 );
if( result > 0 )
strcpy( tmp, "greater than" );
else if( result < 0 )
strcpy( tmp, "less than" );
else
strcpy( tmp, "equal to" );
printf( "\t_stricmp: String 1 is %s string 2\n", tmp );
}

结果当然是1啦。。
int strcmp( const char *string1, const char *string2 );
< 0 string1 less than string2
0 string1 identical to string2
> 0 string1 greater than string2

按照的是字典顺序。

回答2:

从第一个开始比较,如果一样大,就比较第二个,如果一样大,就比较第三个,直到结束或者分出大小为止。