int strncmp ( const char * str1, const char * str2, size_t n );
【參數】str1, str2 為需要比較的兩個字元串,n為要比較的字元的數目。
字元串大小的比較是以ASCII 碼錶上的順序來決定,此順序亦為字元的值。strncmp()首先將s1 第一個字元值減去s2 第一個字元值,若差值為0 則再繼續比較下個字元,直到字元結束標誌'\0',若差值不為0,則將差值返回。例如字元串"Ac"和"ba"比較則會返回字元"A"(65)和'b'(98)的差值(-33)。注意:要比較的字元包括字元串結束標誌'\0',而且一旦遇到'\0'就結束比較,無論n是多少,不再繼續比較後邊的字元。
【返回值】若str1與str2的前n個字元相同,則返回0;若s1大於s2,則返回大於0的值;若s1 小於s2,則返回小於0的值。
基本介紹
- 外文名:strncmp
- 作用:比較s1和s2字元串
- 屬性:函式
- 定義:指定比較size個字元
功 能
用 法
例子
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("buffer2 is greater than buffer1\n");elseif(ptr<0)printf("buffer2 is less than buffer1\n");ptr=strncmp(buf2,buf3,3);if(ptr>0)printf("buffer2 is greater than buffer3\n");elseif(ptr<0)printf("buffer2 is less than buffer3\n");return(0);}
ouput:buffer2 is greater than buffer1buffer2 is less than buffer3
Example 2
/*strncmpexample*/#include<stdio.h>#include<string.h>int main(){char str[][5]={"R2D2","C3PO","R2A6"};int n;puts("Looking for R2 as tromechdroids...");for(n=0;n<3;n++){if(strncmp(str[n],"R2xx",2)==0){printf("found%s\n",str[n]);}}return0;}
ouput:Looking for R2 as tromechdroids...foundR2D2foundR2A6
PHP中
int strncmp(stringstr1,charstr2,intlen);
<?php$str1="Ilikephp!";$str2="ianfine!";echo strncmp($str1,$str2,2);?>