函數(shù)簡介原型:extern int strcmp(const char *s1,const char * s2); 用法:#include <string.h> 功能:比較字符串s1和s2。 說明: 當(dāng)s1<s2時,返回值<0 ; 當(dāng)s1=s2時,返回值=0 ; 當(dāng)s1>s2時,返回值>0 , 即:兩個字符串自左向右逐個字符相比(按ASCII值大小相比較),直到出現(xiàn)不同的字符或遇'\0'為止。如: "A"<"B" "a">"A" "computer">"compare" 特別注意:strcmp(const char *s1,const char * s2)這里面只能比較字符串,不能比較數(shù)字等其他形式的參數(shù)?!≡停篹xtern int strcmp(const char *s1,const char * s2);
用法:#include <
string.h>
功能:比較字符串s1和s2。
一般形式:strcmp(字符串1,字符串2)
說明:
當(dāng)s1<s2時,返回值<0
當(dāng)s1=s2時,返回值=0
當(dāng)s1>s2時,返回值>0
即:兩個字符串自左向右逐個字符相比(按ASCII值大小相比較),直到出現(xiàn)不同的字符或遇'\0'為止。如:
"A"<"B" "a">"A" "computer">"compare"
特別注意:strcmp(const char *s1,const char * s2)這里面只能比較字符串,不能比較數(shù)字等其他形式的參數(shù)。
一例實現(xiàn)代碼:
#include <string.h>
#include <memcopy.h>
#undef strcmp
int
strcmp (p1, p2)
const char *p1;
const char *p2;
{
register const unsigned char *s1 = (const unsigned char *) p1;
register const unsigned char *s2 = (const unsigned char *) p2;
unsigned reg_char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
libc_hidden_builtin_def (strcmp)
編輯本段應(yīng)用舉例
舉例1:(在VC6.0中運行通過)
#include<stdio.h>
#include<string.h>
void main()
{
char string[20];
char str[3][20];
int i;
for(i=0;i<3;i++)
gets(str[i]);
if(strcmp(str[0],str[1])>0)
strcpy(string,str[0]);
else
strcpy(string,str[1]);
if(strcmp(str[2],string)>0)
strcpy(string,str[2]);
printf("\nThe largest string is %s\n",string);
}
舉例2:(TC中運行通過)
// strcmp.c
#include <syslib.h>
#include <string.h>
int main()
{
char *s1="Hello, Programmers!";
char *s2="Hello, programmers!";
int r;
clrscr();
r=strcmp(s1,s2);
if(!r)
printf("s1 and s2 are identical");
else
if(r<0)
printf("s1 less than s2");
else
printf("s1 greater than s2");
getchar();
return 0;
}
strcmp — 二進制安全字符串比較
說明
int
strcmp ( string$str1 , string$str2 )
注意該比較區(qū)分大小寫。
參數(shù)
str1 第一個字符串。
str2 第二個字符串。
返回值
如果
str1 小于
str2,返回負(fù)數(shù);如果
str1 大于
str2,返回正數(shù);二者相等則返回 0。