C语言学习笔记-进阶(6)字符串函数2

发布于:2025-03-09 ⋅ 阅读:(20) ⋅ 点赞:(0)

1. strncpy函数的使用

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

Copies the first num characters of source to destination. If the end of the source C string

(which is signaled by a null-character) is found before num characters have been copied,

destination is padded with zeros until a total of num characters have been written to it.

拷贝num个字符从源字符串到⽬标空间。

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

2. strncat函数的使用

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

Appends the first num characters of source to destination, plus a terminating null-character. (将source指向字符串的前num个字符追加到destination指向的字符串末尾,再追加⼀个 \0 字 符)。

If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.(如果source 指向的字符串的长度小于num的时候,只会将字符串中到 \0 的内容追加到destination指向的字符串末尾)。

/* strncat example */
#include <stdio.h>
#include <string.h>
int main ()
{
 char str1[20];
 char str2[20];
 strcpy (str1,"To be ");
 strcpy (str2,"or not to be");
 strncat (str1, str2, 6);
 printf("%s\n", str1);
 return 0;
}

3. strncmp函数的使用

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

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


网站公告

今日签到

点亮在社区的每一天
去签到