规则
当s1<s2时,返回为负数=-1;
当s1=s2时,返回值= 0;
当s1>s2时,返回正数=1。
即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。如:
1."A"<"B" 2."A"<"AB" 3."Apple"<"Banana" 4."A"<"a" 5."compare"<"computer"
int 自己写一个strcmp函数(char *p1, char *p2)
{//缘由https://ask.csdn.net/questions/7437453?spm=1005.2025.3001.5141int a = 0;while (*p1 != '\0' && *p2 != '\0')(*p1 - 'a'>*p2 - 'a' ? a = 1 : *p1 - 'a' < *p2 - 'a' ? a = -1 : a = 0),++p1, ++p2;return a;
}主函数:char a = 'ad', aa = 'ad';std::cin >> a >> aa;std::cout << 自己写一个strcmp函数(&a, &aa);
int 自己写一个strcmp函数(char *p1, char *p2)
{//缘由https://ask.csdn.net/questions/7437453?spm=1005.2025.3001.5141int a = 0;while (*p1 != '\0' || *p2 != '\0')(*p1 > *p2 ? a = 1 : *p1 < *p2 ? a = -1 : a = 0),(*p1 != '\0' ? ++p1 : 0), (*p2 != '\0' ? ++p2 : 0);return a;
}