#ifndef STR_CMP_H
#define STR_CMP_H
int str_ncmp(const char * str1, const char * str2, int n);
#endif
//实现strncmp函数为字符串比较函数,字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。
//其函数声明为int strncmp(const char * str1, const char * str2, size_t n);
//功能是把 str1 和 str2 进行比较,最多比较前 n 个字节,
//若str1与str2的前n个字符相同,则返回0;
//若s1大于s2,则返回大于0的值;
//若s1 小于s2,则返回小于0的值。
#include "str_cmp.h"
#include<stdio.h>
#include <string.h>
#include<windows.h>
int main(int argc, char* argv[])
{
for (int i = 0; i < argc; ++i)
{
printf("%s", argv[i]);
}
int ret = str_ncmp(argv[1], argv[2], atoi(argv[3]));
printf("the return_value is :%d\n", ret);
/*int ret = strncmp(argv[1], argv[2], atoi(argv[3]));
printf("the return_value is :%d\n", ret);*/
system("pause");
return 0;
}
#include "str_cmp.h"
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
//#define MINLEN (strlen(str1)<strlen(str2)?strlen(str1):strlen(str2))
int str_ncmp(const char * str1, const char * str2, int n)
{
//如果字符串是空或者比较长度小于等于0就退出程序
if (NULL == str1 || NULL == str2 || n <= 0)
{
exit(EXIT_FAILURE);
}
char* pos1 = NULL;
char* pos2 = NULL;
pos1 = str1;
pos2 = str2;
int ret = 0;
//当比较的最长长度不为0,且两个字母一样大时遍历字符串
while (0 != n && (*pos1 == *pos2))
{
++pos1;
++pos2;
--n;
}
ret = *pos1 - *pos2;
if (0 == ret)
{
printf("\n");
printf("两个字符串相等:%s\n", str1);
return 0;
}
else if (ret < 0)
{
printf("\n");
printf("最大的字符串是:%s\n", str2);
return -1;
}
else
{
printf("\n");
printf("最大的字符串是:%s\n", str1);
return 1;
}
}