C语言 之 字符串函数strncpy、ctrncat、strncmp函数的使用

文章目录

strncpy函数的使用

函数原型:

char * strncpy ( char * destination, const char * source, size_t num);

++strncpystrcpy的区别是,strncpy可以控制需要拷贝的字符数量++

1.能够拷贝num个字符从源字符串到目标空间。

2.如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。

例子:

复制代码
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[] = "hello fallzzzzz";
	char str2[20];
	strncpy(str2, str1, 5);
	str2[5] = '\0'; //拷贝的时候没有把'\0'拷贝过去,所以手动添加一个'\0'
	printf("str2 = %s", str2);
	return 0;
}

输出结果:

strncat函数的使用

函数原型:

char * strncat ( char * destination, const char * source, size_t num);

++strncatstrcat的区别是能控制需要追加的字符串中的字符个数++

1.将source指向的字符串的前num个字符追加到destination指向的字符串末尾,之后再追加⼀个 \0 字符。

2.如果source 指向的字符串的长度小于num的时候,只会将字符串中到 \0 的内容追加到destination指向的字符串末尾。

例子:

复制代码
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[20] = "hello ";
	char str2[20] = "fallzzzzz";
	strncat(str1, str2, 4);
	printf("str1 = %s", str1);
	return 0;
}

输出结果:

strncmp函数的使用

函数原型:

int strncmp ( const char * str1, const char * str2, size_t num );

++strncmp能够比较两个字符串的前n个字符++

⽐较str1和str2的前num个字符,如果相等就继续往后比较,最多比较num个字母,如果提前发现不⼀样,就提前结束,⼤的字符所在的字符串⼤于另外⼀个。如果num个字符都相等,就是相等返回0。

比较的返回值规则和strcmp的一样,返回值为0则表示相等

例子:

复制代码
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[] = "fall";
	char str2[] = "falll";
	int tmp = strncmp(str1, str2, 4);
	printf("%d", tmp);
	return 0;
}

输出结果:

相关推荐
祈安_3 天前
C语言内存函数
c语言·后端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish5 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人5 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J5 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹45 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow5 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法
Sunsets_Red5 天前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛