admin管理员组

文章数量:1794759

字符串函数(4)字符串函数的限制使用

字符串函数

前面我们讲了strlen、strcat、strcpy、strcmp函数的使用和模拟实现。 hello,我是结衣。今天我们讲字符串函数strcpy、strcat、strcmp函数的限制使用。就是可以自己限制字符的使用数目。 将这些函数中间填加‘n’变为strncpy、strncat、strncmp。

strncpy函数

使用该函数可以将源字符串复制到目的字符串中,并且可以限制复制的字符个数。 格式 char * strncpy ( char * destination, const char * source, size_t num ); 代码

代码语言:javascript代码运行次数:0运行复制
#include <stdio.h>
#include <string.h>
int main()
{
	char ch1[20] = "abc";
	char ch2[] = "abcdef";

	printf("%s\n", strncpy(ch1, ch2,1));//strcpy函数可以限制字符数目。

		return 0;
}

strncat函数

格式和上面一样的 代码

代码语言:javascript代码运行次数:0运行复制
#include <stdio.h>
#include <string.h>
int main()
{
	char ch1[20] = "abc";
	char ch2[] = "abcdef";

	printf("%s\n", strncat(ch1, ch2, 3));//strcat函数可以限制字符数目。

	return 0;
}

strncmp函数

格式 int strncmp ( const char * str1, const char * str2, size_t num ); 代码

代码语言:javascript代码运行次数:0运行复制
#include <stdio.h>
#include <string.h>
int main()
{
	char ch1[20] = "abc";
	char ch2[] = "abcd";

	printf("%d\n", strncmp(ch1, ch2,4));//strcmp函数可以限制字符数目,记得用%d

	return 0;
}

因为代码很简单,结衣相信大家都可以看懂的,就没有过多的解释。这篇文章注意是让大家可以了解一下。 那么就到此结束了,下次在见了。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2023-09-13,如有侵权请联系 cloudcommunity@tencent 删除int函数字符串charinclude

本文标签: 字符串函数(4)字符串函数的限制使用