strncmp 串比较

函数名: strncmp   

功 能: 串比较   

用 法: int strncmp(char *str1, char *str2, int maxlen);   

说明:此函数功能即比较字符串str1和str2的前maxlen个字符。

如果前maxlen字节完全相等,返回值就=0;

在前maxlen字节比较过程中,

如果出现str1[n]与str2[n]不等,

则返回(str1[n]-str2[n])。 

 Example 1:   

#include <string.h>  

#include <stdio.h>   

int main(void)   

{   

        char *buf1 = "aaabbb", *buf2 = "bbbccc", *buf3 = "ccc";

  int ptr;

  ptr = strncmp(buf2,buf1,3);

  if (ptr > 0)

  printf("buffer 2 is greater than buffer 1\n");

  else if(ptr<0)

  printf("buffer 2 is less than buffer 1\n");

  ptr = strncmp(buf2,buf3,3);

  if (ptr > 0)

  printf("buffer 2 is greater than buffer 3\n");

  else if(ptr<0)

  printf("buffer 2 is less than buffer 3\n");

  return(0);

}  

ouput:  

buffer 2 is greater than buffer 1  

buffer 2 is less than buffer 3  

[1]Example 2:  

/* strncmp example */  

#include <stdio.h>  

#include <string.h>  

int main ()  

{

  char str[][5] = { "R2D2" , "C3PO" , "R2A6" };

  int n;

  puts ("Looking for R2 astromech droids...");

  for (n=0 ; n<3 ; n++)

  {

      if (strncmp (str[n],"R2xx",2) == 0)

      {

          printf ("found %s\n",str[n]); 

         }   

           return 0;  

        }

  }  

ouput:  

Looking for R2 astromech droids...  

found R2D2  

found R2A6  

PHP中: 

 函数名: strncmp ()  

功 能:比较字符串的前N个字符 

 用 法: int strncmp(string str1, char str2, int len);

  说明:比较字符串str1和str2的大小,如果str1小于str2,返回值就<0,反之如果str1大于str2,返回值就>0,如果str1等于str2,返回值就=0,len指的是str1与str2的比较的字符数。此函数功能即比较字符串str1和str2的前len个字符。  

提示:该函数区分大小写。 

 示例:<?php  $str1="I like php !"; 

 $str2="i an fine !"; 

 echo strncmp($str1,str2,2); 

 ?>  结果为:-1


你可能感兴趣的:(strncmp 串比较)