完整题干:
写一函数,实现两个字符串的比较。即自己写一个strcmp函数,函数原型为
int strcmp( char * p1, char * p2);
设p1指向字符串s1 ,p2指向字符串s2。要求当s1=s2时,返回值为0,若s1≠s2,返回它们二者第1个不同字符的ASCII码差值(如"BOY"与"BAD" ,第2个字母不同, " O"与"A"之差为79-65 =14)。如果s1 >s2,则输出正值,如s1 <s2,则输出负值。
个人答案:
#include <iostream>
using namespace std;
int strcmp(char* p1, char* p2);
int main()
{
char s1[20], s2[20];
cout << "Please enter string s1: ";
cin>>s1;
cout << "Please enter string s2: ";
cin>>s2;
cout << "Result: " << strcmp(s1, s2) << endl;
system("pause");
return 0;
}
int strcmp(char* p1, char* p2)
{
int t;
for (; *p1 != '\0' || *p2 != '\0'; p1++, p2++)
if (*p1 != *p2) {
t = *p1 - *p2;
break;
}
if (*p1 == '\0' && *p2 == '\0')
t = 0;
return t;
}
结果: