【C】库函数之strcat

Concatenate strings

  Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

  destination and source shall not overlap.

   上述内容是C++官网对strcat函数的介绍,可以看出strcat函数将源字符串的内容连接到目标字符串后面,而目标字符串中的终止空字符被源字符串的第一个字符覆盖,新字符串的末尾包含一个空字符。需要注意的是,目标字符串不能与源字符串重叠

  接下来给出实现strcat函数的源代码:

#define _CRT_SECURE_NO_WARNINGS 1

/*
* Copyright (c) 2018, code farmer from sust
* All rights reserved.
*
* 文件名称:MyStrcat.c
* 功能:实现库函数strcat
*       char * strcat ( char * destination, const char * source )
*
* 当前版本:V1.0
* 作者:sustzc
* 完成日期:2018年4月20日11:38:57
*/

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

/*
*	函数名称:MyStrcat
*
*	函数功能:将源字符串的内容连接到目标字符串后面,
*            目标字符串中的终止空字符被源字符串的第一个字符覆盖,
*            新字符串的末尾包含一个空字符。 
*
*	入口参数:dest, src
*
*	出口参数:dest
*
*	返回类型:char *
*/

char * MyStrcat(char * dest, const char * src)
{
	char * cp = dest;

	assert((NULL != src) && (NULL != cp));
		
	while ('\0' != *cp)
	{
		cp++;
	}
	while (*cp++ = *src++)
	{
		;
	}

	return dest;
}

int main(void)
{
	char str1[10] = "abc";
	char *str2 = "123";

	printf("str1: %s\n", str1);
	printf("str2: %s\n", str2);
	printf("connect after,str1: %s\n", MyStrcat(str1, str2));

	return 0;
}

输出结果


猜你喜欢

转载自blog.csdn.net/sustzc/article/details/80017153