C语言中的strncpy()函数是什么?


C库函数 **char *strncpy(char *dest, const char *src, size_t n)** 将最多 n 个字符从 **src** 指向的字符串复制到 **dest**。如果 src 的长度小于 n,则 dest 的其余部分将用空字节填充。

字符数组称为字符串。

声明

以下是数组的声明:

char stringname [size];

例如:char string[50]; 长度为50个字符的字符串

初始化

  • 使用单字符常量:
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • 使用字符串常量:
char string[10] = "Hello":;

**访问**:使用控制字符串“%s”访问字符串,直到遇到‘\0’。

strncpy() 函数

  • 此函数用于将源字符串的 n 个字符复制到目标字符串中。

  • 目标字符串的长度大于或等于源字符串。

语法如下:

strncpy (Destination string, Source String, n);

示例程序

以下是strncpy()函数的C程序:

#include<string.h>
main ( ){
   char a[50], b[50];
   printf ("enter a string");
   gets (a);
   strncpy (b,a,3);
   b[3] = '\0';
   printf ("copied string = %s",b);
   getch ( );
}

输出

执行上述程序后,将产生以下结果:

Enter a string : Hello
Copied string = Hel

它也用于提取子字符串。

示例1

以下示例演示了strncpy()函数的用法。

char result[10], s1[15] = "Jan 10 2010";
strncpy (result, &s1[4], 2);
result[2] = ‘\0’

输出

执行上述程序后,将产生以下结果:

Result = 10

示例2

让我们看看另一个关于strncpy的例子。

下面是一个C程序,使用strncpy库函数将n个字符从源字符串复制到目标字符串:

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring source and destination strings//
   char source[45],destination[50];
   char destination1[10],destination2[10],destination3[10],destination4[10];
   //Reading source string and destination string from user//
   printf("Enter the source string :");
   gets(source);
   //Extracting the new destination string using strncpy//
   strncpy(destination1,source,2);
   printf("The first destination value is : ");
   destination1[2]='\0';//Garbage value is being printed in the o/p because always assign null value before printing O/p//
   puts(destination1);
   strncpy(destination2,&source[8],1);
   printf("The second destination value is : ");
   destination2[1]='\0';
   puts(destination2);
   strncpy(destination3,&source[12],1);
   printf("The third destination value is : ");
   destination3[1]='\0';
   puts(destination3);
   //Concatenate all the above results//
   strcat(destination1,destination2);
   strcat(destination1,destination3);
   printf("The modified destination string :");
   printf("%s3",destination1);//Is there a logical way to concatenate numbers to the destination string?//
}

输出

执行上述程序后,将产生以下结果:

Enter the source string :Tutorials Point
The first destination value is : Tu
The second destination value is : s
The third destination value is : i
The modified destination string :Tusi3

更新于:2021年3月19日

755 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.