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

输出结果:

相关推荐
Tandy12356_5 分钟前
手写TCP/IP协议——IP层输出处理
c语言·网络·c++·tcp/ip·计算机网络
龚礼鹏9 小时前
Android应用程序 c/c++ 崩溃排查流程
c语言·开发语言·c++
路弥行至14 小时前
FreeRTOS任务管理详解中: FreeRTOS任务创建与删除实战教程(动态方法)
c语言·开发语言·笔记·stm32·操作系统·freertos·入门教程
了一梨15 小时前
外设与接口:input子系统
linux·c语言
我是华为OD~HR~栗栗呀15 小时前
23届(华为od)-C开发面经
java·c语言·c++·python·华为od·华为·面试
liu****15 小时前
8.栈和队列
c语言·开发语言·数据结构·c++·算法
松涛和鸣16 小时前
27、Linux标准IO深度解析:缓冲区机制与文件定位
服务器·c语言·前端·数据结构·算法·哈希算法
embrace9917 小时前
【C语言学习】动态内存管理
java·c语言·开发语言·c++·学习·算法·链表
小刘爱玩单片机18 小时前
【stm32简单外设篇】- HC-SR04 超声波测距模块
c语言·stm32·单片机·嵌入式硬件
小刘爱玩单片机18 小时前
【stm32简单外设篇】– L9110S 与 L298N 电机驱动器
c语言·stm32·单片机·嵌入式硬件