c语言模拟实现strncat

       在c语言的库函数中,strcat负责将一个字符串加在另一个字符串的后面,但他只能将一个字符串的所有字符加在另一字符串的后面,而strncat则可以选择性的在字符串后加字符串,使追加字符串更灵活,更安全。
       在选择性的追加字符串前,要先知道两个字符串的长度,且被追加的字符串的后面有足够的空间来接收所追加的字符串,所以被追加字符串的必须是数组才能接收字符串。
       在追加前,必须让被追加的字符串的指针指向被追加的字符串的后面,这样才不会让原有的字符串被覆盖,然后再逐一追加字符串。
       在追加字符串时,要比较所追加的字符串的长度与你想追加的长度的的长短,如果大于你所想追加的字符串长度,则要在最终完成的字符串后加上'\0',反之则在遇到'\0'后停止追加。

#include<stdio.h>
#include<assert.h>
int SIZEOF(char* asd)
{
	int j = 0;
	while (*asd!='\0')
	{
		j++;
		asd++;
	}
	return j;
}
char* my_strncat(char*tat,const char*ant, int num)
{
	assert(tat&&ant);
	int ssz = SIZEOF(tat);
	int ass = SIZEOF(ant);
	tat = tat + ssz;
	if (ass < num)
	{
		int i=0;
		for (i = 0; i < ass; i++)
		{
			*tat = *ant;
			tat++;
			ant++;
		}
		return tat ;
	}
	else
	{
		int i = 0;
		for (i = 0; i < num; i++)
		{
			*tat = *ant;
			tat++;
			ant++;
		}
		return tat + '\0';

	}
}
int main()
{
	char arr1[20] = "hello ";
	char *arr2 = "word";
	int sz = 0;
	scanf_s("%d", &sz);
	my_strncat(arr1, arr2, sz);
	printf("%s", arr1);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/f_shell_x/article/details/81240641