函數名: strncmp
頭檔:<string.h>
函式原型: int strncmp(const char *str1,const char *str2,int n);
功 能: 對指定字串數量的兩個字串進行比較
參 數: str1和str2 為要進行比較的字串
int n 為要比較的字串個數
傳回值: str1 > str2 傳回大於0的值;
str1==str2 傳回等於0的值;
str1 < str2 傳回小於0的值;
注意:此函數傳回的不是1或-1這樣的固定值,而是大於0或小於0的值
程式例:將字串s2分別於字串s1和s3的前n個字元進行比較,並把結果輸出
#include<stdio.h>#include<string.h>intmain(void){char*s1=www.dotcpp,*s2=dotcpp.com,*s3=dotcpp;intp=strncmp(s2,s1,3); if(p>0){printf(s2isgreaterthans1n);}elseif(p<0){printf(s2islessthans1n);}else{printf(s2isequalss1n);}p=strncmp(s2,s3,3) ;if(p>0){printf(s2isgreaterthans3n);}elseif(p<0){printf(s2islessthans3n);}else{printf(s2isequalss3n);}return0;}運行結果:
s2islessthans1s2isequalss3