str类函数的实现0.3——strcmp/strncmp

strcmp函数原型:extern int strcmp(const char *s1,const char * s2);在头文件:string.h中,
功能:比较字符串s1和s2。

说明:当s1<s2时,返回为负数 ;当s1==s2时,返回值= 0;当s1>s2时,返回正数。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int my_strcmp(const char*s1,const char*s2)
{
	assert(s1);
	assert(s2);
	while(*s1 == *s2)
	{
		s1++;
		s2++;
		if((*s1 == '\0')&&(*s2 == '\0'))
			return 0;
	}
	if (*s1 > *s2)
		return 1;
	else
		return -1;
}

int main()
{
	int my_strcmp(const char*s1,const char*s2);
	int my_strncmp(const char*s1,const char*s2,int count);
	char *str = "ccdefh";
	char *buf = "ccdfbc";
	printf("%d ",my_strcmp(str,buf));
	printf("%d ",my_strncmp(str,buf,66));
	system("pause");
	return 0;
}


strncmp() 用来比较两个字符串的前n个字符,区分大小写,其原型为:

    int strncmp ( const char * str1, const char * str2, size_t n );

int my_strncmp(const char*s1,const char*s2,int count)
{
	int i = 0;
	assert(s1);
	assert(s2);
	for(;i<count;i++,s1++,s2++)
	{
		if(*s1 == *s2)
			;
		if (*s1 > *s2)
		{return 1;}
	    if (*s1 < *s2)
	    {return -1;}
    }return 0;


猜你喜欢

转载自blog.csdn.net/erica_ou/article/details/53078703