C ++ implement strcmp function, two string comparison
mission details
Write a function to compare two strings.
That is, write a strcmp function yourself, the function prototype is int strcmp (char * p1, char * p2);
Let p1 point to string s1 and p2 point to string s2. It is required that when s1 = s2, the return value is 0, if s1! = S2, the ASCII code difference of the first different characters of the two is returned (such as "BOY" and "BAD", the second letter is different, "O The difference between "" and "A" is 79-65 = 14). If s1> s2, output a positive value, such as s1 <s2, output a negative value.
Test input:
abc def
Expected output:
result:-3
Test input:
aaa AAA
Expected output:
result:32
Source code:
#include <iostream>
using namespace std;
int main()
{
int strcmp(char *p1,char *p2);
// 请在此添加代码
/********** Begin *********/
char a[100],b[100];
cin>>a>>b;
cout<<"result:"<<strcmp(a,b);
/********** End **********/
return 0;
}
int strcmp(char *p1,char *p2) //自已定义字符串比较函数
{
// 请在此添加代码
/********** Begin *********/
while(*p1 && (*p1==*p2)){
++p1;
++p2;
}
return *p1 - *p2;
/********** End **********/
}