【C语言进阶:刨根究底字符串函数】 strcat 函数

本节重点内容:

  • 深入理解strcat函数的使用
  • 学会strcat函数的模拟实现

⚡strcat

  • Appends a copy of the source string to the destination string. The terminating null characterin destination is overwritten by the first character of source, and a null-character is includedat the end of the new string formed by the concatenation of both in destination.
  •  源字符串必须以 '\0' 结束。
  • 目标空间必须有足够的大,能容纳下源字符串的内容。
  • 目标空间必须可修改。
  • strcat字符串不能自己给自己追加,会陷入无限追加。

strcat的基本使用:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char arr1[20] = "hello ";
	char arr2[] = "world";
	strcat(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}

运行结果如下:

strcat函数的原理:从目的地字符串的 ‘\0’ 的位置开始追加,把 ‘\0’ 覆盖掉一直追加,直到将源头的字符串内容全部拷贝到目的地,包括 ’\0‘ 。

验证代码示例如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>

int main()
{
	char arr1[20] = "hello \0xxxxxxxx";
	char arr2[] = "world";
	strcat(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}

运行结果如下:


⚡模拟实现strcat函数 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>
#include<assert.h>

char* my_strcat(char* dest, const char* src)
{
	assert(dest && src);
	char* start = dest;
	while (*dest != '\0') //找出\0
	{
		dest++;
	}
	while (*dest++ = *src++) //拷贝字符串
	{
		;
	}
	return start;
}

int main()
{
	char arr1[20] = "hello \0xxxxxxxx";
	char arr2[] = "world";
	my_strcat(arr1, arr2);
	printf("%s\n", arr1);
	return 0;
}

运行结果如下:


感谢大家能够看完这篇博客,创作时长,小伙伴们觉得我的博客对你有帮助,不妨留下你的点赞的收藏,关注我,带你了解不一样的C语言。

98b76a6f4a9c4ca88fd93da1188ac6f9.gif

猜你喜欢

转载自blog.csdn.net/JX_BC/article/details/129594476
今日推荐