strncmp ()- 比較字串

格式

#include <string.h>
int strncmp(const char *string1, const char *string2, size_t count);

語言層次

ANSI

安全執行緒

說明

strncmp() 函數會將 string1string2 與最大值 count進行比較。

回覆值

strncmp() 函數會傳回一個值,指出字串之間的關係,如下所示:
Value 意義
小於 0 string1 小於 string2
0 string1 相當於 string2
大於 0 string1 大於 string2

範例

此範例示範 strcmp() 函數與 strncmp() 函數之間的差異。
#include <stdio.h>
#include <string.h>
 
#define SIZE 10
 
int main(void)
{
  int  result;
  int  index = 3;
  char buffer1[SIZE] = "abcdefg";
  char buffer2[SIZE] = "abcfg";
  void print_result( int, char *, char * );
 
  result = strcmp( buffer1, buffer2 );
  printf( "Comparison of each character\n" );
  printf( "  strcmp: " );
  print_result( result, buffer1, buffer2 );
 
  result = strncmp( buffer1, buffer2, index);
  printf( "\nComparison of only the first %i characters\n", index );
  printf( "  strncmp: " );
  print_result( result, buffer1, buffer2 );
}
 
void print_result( int res, char * p_buffer1, char * p_buffer2 )
{
  if ( res == 0 )
    printf( "\"%s\" is identical to \"%s\"\n", p_buffer1, p_buffer2);
  else if ( res < 0 )
    printf( "\"%s\" is less than \"%s\"\n", p_buffer1, p_buffer2 );
  else
    printf( "\"%s\" is greater than \"%s\"\n", p_buffer1, p_buffer2 );
}
 
/*****************  Output should be similar to:  *****************
 
Comparison of each character
  strcmp: "abcdefg" is less than "abcfg"
 
Comparison of only the first 3 characters
  strncmp: "abcdefg" is identical to "abcfg"
*/

相關資訊