模拟实现strncmp
注意strcmp只比较len个字符是否相等,这里给出了两种方法:
ps:我在调试过程中遇到了前置、后置++问题,结合前置、后置++的特性,通过理清判断和自增的顺序来决定使用哪一种++,最好的办法就是多调试走几遍代码,理清每一步的顺序和结果
程序代码如下:
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//减法运算判断
int MyStrncmp1(const char *src, const char *dest, size_t len)
{
assert(NULL != dest && NULL != src);
int ret = 0;
//这里使用后置--,因为ret是在src、dest向后自增之前进行减法运算判断的
while (len-- && !(ret = *(unsigned char *)src - *(unsigned char *)dest) && *dest)
{
src++;
dest++;
}
if (ret < 0)
{
ret = -1;
}
else if (ret > 0)
{
ret = 1;
}
return ret;
}
//比较运算判断
int MyStrncmp2(const char* dest, const char* src, size_t len)
{
assert(NULL != dest && NULL != src);
//这里使用前置--,因为ret是在src、dest向后自增之前进行减法运算判断的
while (--len && (*dest) && (*src == *dest))
{
*dest++;
*src++;
}
if (*(unsigned char*)dest > *(unsigned char*)src)
return 1;
else if (*(unsigned char*)dest < *(unsigned char*)src)
return -1;
else
return 0;
}
int main()
{
char str1[8] = "hehao";
char str2[6] = "hello";
printf("%d\n", MyStrncmp1(str1, str2,2));//前两个字符相等 1
printf("%d\n", MyStrncmp1(str1, str2, 3));//前三个字符不相等 -1
printf("%d\n", MyStrncmp1("he", "hello",3));//dest长度小于len
printf("%d\n\n", MyStrncmp1("hello", "he",3));//src长度小于len
printf("%d\n", MyStrncmp2(str1, str2, 2));
printf("%d\n", MyStrncmp2(str1, str2, 3));
printf("%d\n", MyStrncmp2("he", "hello", 3));
printf("%d\n\n", MyStrncmp2("hello", "he", 3));
system("pause");
return 0;
}
程序运行结果如下: