暑假没什么事,想着多学习C语言知识,想起完成一个字符串比较函数。
以前也有作为考试题给出的。今天我也完成自己的字符串比较函数。
int strcmp_1(char *res, char *dest)
当res大于dest时,返回1;
当res小于dest时,返回-1;
当res等于dest时,返回0;
根据这样的思路完成本题代码。
代码如下:
#include <stdio.h>
#include <string.h>
int strcmp_1(char *res, char *dest);
void main()
{
char p1[50],p2[50],res=0;
gets(p1); // 获取字符串p1
gets(p2); // 获取字符串p2
res = strcmp_1(p1,p2);
printf("res is : %d\n",res);
}
/* 两个字符串比较函数 */
int strcmp_1(char *res, char *dest)
{
int len1,len2,i;
len1 = strlen(res);
len2 = strlen(dest);
if(len1<len2)
{
for(i=0; i<len1; i++)
{
if(*(res+i)>*(dest+i))
{
return 1;
}
else if(*(res+i)<*(dest+i))
{
return -1;
}
}
return -1;
}
else if(len1>len2)
{
for(i=0; i<len2; i++)
{
if(*(res+i)>*(dest+i))
{
return 1;
}
else if(*(res+i)<*(dest+i))
{
return -1;
}
}
return 1;
}
else
{
for(i=0; i<len2; i++)
{
if(*(res+i)>*(dest+i))
{
return 1;
}
else if(*(res+i)<*(dest+i))
{
return -1;
}
}
return 0;
}
}
这样就完成 了本题的思想,但代码有很多优化的地方,等以后我会作进一步优化。
代码运行结果为: