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;
}

输出结果:

相关推荐
SmartRadio5 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
SmartRadio12 小时前
在CH585M代码中如何精细化配置PMU(电源管理单元)和RAM保留
linux·c语言·开发语言·人工智能·单片机·嵌入式硬件·lora
jimy113 小时前
C语言里面的中断程序:“exit()”和“return返回”
c语言
SmartRadio13 小时前
进一步优化CH585M的低功耗模式
c语言·开发语言·单片机·嵌入式硬件·物联网
清水白石00815 小时前
深入 Python 的底层世界:从 C 扩展到 ctypes 与 Cython 的本质差异全解析
c语言·python·neo4j
进击中的小龙16 小时前
基于rtklib的载波相位平滑伪距
c语言·算法·数学建模·gitee
程序员zgh16 小时前
Linux 系统调用
linux·运维·服务器·c语言·c++·系统安全
情缘晓梦.17 小时前
C语言数据存储
c语言·开发语言
SmartRadio18 小时前
MK8000(UWB射频芯片)与DW1000的协议适配
c语言·开发语言·stm32·单片机·嵌入式硬件·物联网·dw1000
消失的旧时光-194318 小时前
从 C 对象模型 → JNI → HAL → Linux 内核接口——一条贯穿系统软件的完整认知链
linux·c语言·开发语言