菜鸟笔记
提升您的技术认知

strncpy,strncat,strncmp函数的介绍

strncpy

char * strncpy ( char * destination, const char * source, size_t num );
  • 拷贝num个字符从源字符串到目标空间
  • 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标后边追加0,直到num个。

strncat

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

举个栗子说明一下:

#include<stdio.h>
#include<windows.h>
int main()
{
	char str1[20];
	char str2[20];
	strcpy(str1, "to be");
	strcpy(str2, "or not to be");
	strncat(str1, str2, 6);
	puts(str1);
	system("pause");
	return 0;
}

strncmp

int strncmp ( const char * str1, const char * str2, size_t num ); 
  • 比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。

举个栗子感受一下:

#include<stdio.h>
#include<windows.h>
int main()
{
	char str[][5] = { "R2D2", "C3PO", "R2A6" };
	int n;
	puts("Looking for R2 astromech droids...");
	for (n = 0; n < 3; n++)
	{
		if (strncmp(str[n], "R2xx", 2) == 0)
		{
			printf("found %s\n", str[n]);
		}
	}
	system("pause");
	return 0;
}