strcmp函数是string compare(字符串比较)的缩写,用于比较两个字符串并根据比较结果返回整数;
strcmp(str1,str2);
若str1=str2,则返回零;若str1<str2,则返回负数;若str1>str2,则返回正数;
比较规则:
两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止;
如:
"A"<"B"
"A"<"AB"
"Apple"<"Banana"
"A"<"a"
"compare"<"computer"
VC6版本,
void CCmpView::OnDraw(CDC* pDC)
{
CCmpDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CString str1;
char *s1="Hello,301";
char *s2="Hello,402";
int r;
r = strcmp(s1,s2);
str1.Format("比较结果:%d",r);
pDC->TextOut(50, 50, str1);
if(!r)
pDC->TextOut(50, 80, "s1和s2相同");
else if(r<0)
pDC->TextOut(50, 80, "s1小于s2");
else
pDC->TextOut(50, 80, "s1大于s2");
}
控制台版本,
#include <stdio.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;
}