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.