模拟实现strncpy strncat strncmp

什么是strncpy函数:

strncpy是c语言的一个库函数,定义与string.h char* strncpy(char* dst,const char* src,int n)

它的作用是将字符串以src地址前的前n个字符拷贝到dst所指的数组中,并返回dst

strncpy在拷贝时,会将‘\0’也拷贝出来,并以‘\0’作为循环的终止条件。这样子就会避免程序自己崩掉的情况发生。

#include<stdio.h>
#include<assert.h>


char* my_strncpy(char *dst, const char *src, int count)
{
	char *p = dst;
	assert(src && dst);
	while (count && (*dst ++= *src++))
	{
		count--;
	}
	if (count > 0)
	{
		while (--count)
		{
			*dst++ = '\0';
		}
	}
	return p;
}

int main()
{
	char string[80] = { 0 };
	int len = strlen("hello");
	printf("String = %s\n", my_strncpy(string, "Hello", len));
	system("pause");
	return 0;
}

什么是strncat函数?

它的函数原型是char* strncat(char* dst,const char* src,size_t n)

它的作用是在字符串结尾追加n个字符

#include<stdio.h>
#include<assert.h>

char* my_strncat(char* dst, const char* src, int count)
{
	char *p = dst;
	assert(src && dst);
	while (*dst != '\0')
	{
		*dst++;
	}
	while (count && *src)
	{
		*dst++ = *src++;
		count--;
	}
	*dst = '\0';
	return p;
}

int main()
{
	char a[32] = "world";
	int len = strlen(a);
	char* ret = my_strncat(a, a, len);
	printf("%s", ret);
	system("pause");
	return 0;
}

什么是strncmp函数?

它的原型是char*(const char* str1,const char* str2,size_t n)

它的作用和strcmp很相似,它的作用是:str1, str2 为需要比较的两个字符串,n为要比较的字符的数目。

通过ASCII码来比较,若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 若小于s2,则返回小于0的值。

#include<stdio.h>
#include<assert.h>
char* my_strncmp(const char* a, const char* b, int count)
{
	assert(a&&b);
	while (count && (*a == *b))
	{
		if (a == '\0')
			return 0;
		a++;
		b++;
		count--;
	}
	return *a - *b;
}

int main()
{
	char *a = "abcd";
	char *b = "abcdefc";
	int len = strlen(a);
	int ret = my_strncmp(a, b, len);
	printf("%d\n", ret);
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/LSFAN0213/article/details/80627444
今日推荐