(轉)strncmp, wcsncmp詳解

Parameters

string1, string2
Strings to compare.
count
Number of characters to compare.

Return Values

The return value indicates the relation of the substrings of string1 and string2 as follows.

Return Value Description
< 0 string1 substring less than string2 substring
0 string1 substring identical to string2 substring
> 0 string1 substring greater than string2 substring

Remarks

The strncmp function lexicographically compares, at most, the first count characters in string1 and string2 and returns a value indicating the relationship between the substrings. strncmp is case-sensitive. Unlike strcoll, strncmp is not affected by locale.

wcsncmp is the wide-character version of strncmp. The arguments and return value of wcsncmp are wide-character strings. These two functions behave identically otherwise. wcsncmp is the case-sensitive version of _wcsnicmp.

Generic-Text Routine Mappings

TCHAR.H Routine _UNICODE Defined
_tcsnccmp wcsncmp
_tcsncmp wcsncmp

For more information about TCHAR.H routines, see Generic Text Mappings.

Example

/* STRNCMP.C */
#include <string.h>
#include <stdio.h>

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

void main( void )
{
   char tmp[20];
   int result;
   printf( "Compare strings:/n/t/t%s/n/t/t%s/n/n", string1, string2 );
   printf( "Function:/tstrncmp (first 10 characters only)/n" );
   result = strncmp( string1, string2 , 10 );
   if( result > 0 )
      strcpy( tmp, "greater than" );
   else if( result < 0 )
      strcpy( tmp, "less than" );
   else
      strcpy( tmp, "equal to" );
   printf( "Result:/t/tString 1 is %s string 2/n/n", tmp );
   printf( "Function:/tstrnicmp _strnicmp (first 10 characters only)/n" );
   result = _strnicmp( string1, string2, 10 );
   if( result > 0 )
      strcpy( tmp, "greater than" );
   else if( result < 0 )
      strcpy( tmp, "less than" );
   else
      strcpy( tmp, "equal to" );
   printf( "Result:/t/tString 1 is %s string 2/n/n", tmp );
}

Output

Compare strings:
      The quick brown dog jumps over the lazy fox
      The QUICK brown fox jumps over the lazy dog

Function:   strncmp (first 10 characters only)
Result:      String 1 is greater than string 2

Function:   _strnicmp (first 10 characters only)
Result:      String 1 is equal to string 2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章