在C/C++库函数中,实现字符串的比较使用strcmp函数,
其函数接口为:int strcmp(char *str1,char *str2);
现自己定义一个函数实现字符串比较。
C代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
字符串比较:int MyStrcmp(char *str1, char *str2){}
1、str1大于str2,返回值为1
2、str1小于str2,返回值为-1
3、str1等于str2,返回值为0
*/
int MyStrcmp(const char *str1, const char *str2) {
if (str1 == NULL || str2 == NULL) {
printf("Error!");
exit(0);
}
while (*str1 != '\0'&&*str2 != '\0'&&*str1 == *str2) {
str1++;
str2++;
}
if (*str1 != '\0'&&*str2 == '\0') {
return 1;
}
else if (*str1 == '\0'&&*str2 != '\0') {
return -1;
}
else if (*str1 > *str2) {
return 1;
}
else if (*str1 < *str2) {
return -1;
}
else {
return 0;
}
}
int main() {
char str1[50];
char str2[50];
printf("Please input str1:");
scanf("%s", str1);
printf("Please input str2:");
scanf("%s", str2);
printf("Result:");
if (MyStrcmp(str1, str2)>0) {
printf("%s > %s", str1, str2);
}
else if (MyStrcmp(str1, str2)<0) {
printf("%s < %s", str1, str2);
}
else {
printf("%s = %s", str1, str2);
}
getchar();
getchar();
printf("\n");
}
C运行结果:
说明:第18-21行代码不可写成如下形式
while (*str1 != '\0'&&*str2 != '\0'&&*str1++ == *str2++) {
}
否则,容易出错。
错误原因是:若发现 * str1 != * str2,多执行了str1++、str2++,这时从while循环出来比较的是自增后的str1和str2。
分析下边错误例子:当str1指向c,str2指向d,这时 * str1 != * str2,然而跳出循环时,str1和str2均发生自增,指向的是尾结束符‘\0’,因此比较时出现了错误。