C 庫 - strcpy() 函式



C 庫的 strcpy() 函式接受兩個引數,將 src 指向的字串複製到 dest。此函式對於維護和升級舊系統至關重要。

語法

以下是 C 庫 strcpy() 函式的語法:

char *strcpy(char *dest, const char *src)

引數

此函式接受以下引數:

  • dest - 這是指向目標陣列的指標,內容將被複制到該陣列。

  • src - 這是要複製的字串。

確保目標陣列有足夠的空間容納源字串,包括空終止符。

返回值

此函式返回指向目標字串 dest 的指標。

示例 1

以下是一個基本的 C 程式,演示了 strcpy() 函式的使用。

#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[100];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strcpy(dest, src);

   printf("Final copied string : %s\n", dest);
   
   return(0);
}

輸出

執行上述程式碼後,我們將獲得以下輸出:

Final copied string : This is tutorialspoint.com

示例 2

下面的示例展示了自定義字串複製,不使用 strcpy()。

#include <stdio.h>
void customStrcpy(char* dest, const char* src) {
   while (*src) {
       *dest = *src;
       dest++;
       src++;
   }
   *dest = '\0';
}

int main() {
   char source[] = "string Copy!";
   char destination[20];
   customStrcpy(destination, source);

   printf("The custom copied string: %s\n", destination);

    return 0;
}

輸出

執行上述程式碼後,我們將獲得以下輸出:

The custom copied string: string Copy!

示例 3

在這裡,我們定義了兩個字串變數 - source 和 destination。然後應用 strcpy(),它接受這兩個變數來確定字串複製的結果。

#include <stdio.h>
#include <string.h>

int main() {
   char source[] = "Hello, World!";
   char destination[20];

   strcpy(destination, source);
   printf("The result of copied string: %s\n", destination);

   return 0;
}

輸出

上述程式碼產生以下輸出:

The result of copied string: Hello, World!
廣告