C語言中的strcpy()函式是什麼?
C 庫函式 char *strcpy(char *dest, const char *src) 將 src 指向的字串複製到 dest 中。
字元陣列稱為字串。
宣告
以下是陣列的宣告
char stringname [size];
例如 − char string[50]; 字串的長度為 50 個字元
初始化
- 使用單個字元常量 −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字串常量 −
char string[10] = "Hello":;
訪問 − 有一個控制字串 "%s" 用於訪問字串,直到它遇到‘\0’
strcpy () 函式
此函式用於將源字串複製到目標字串中。
目標字串的長度大於或等於源字串的長度。
語法
語法如下 −
strcpy (Destination string, Source String);
示例
以下示例顯示了 strcpy() 函式的用法。
char a[50]; char a[50];
strcpy ("Hello",a); strcpy ( a,"hello");
output: error output: a= "Hello"程式
以下程式顯示了 strcpy() 函式的用法。
#include <string.h>
main ( ){
char a[50], b[50];
printf ("enter a source string");
scanf("%s", a);
strcpy ( b,a);
printf ("copied string = %s",b);
getch ( );
}輸出
執行上述程式後,它會產生以下結果 −
Enter a source string : Hello Copied string = Hello

讓我們來看另一個有關 strcpy 的示例。
以下是演示 strcpy 庫函式的 C 程式 −
程式
#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[25],destination[50];
//Reading Input from user//
printf("Enter the string to be copied : ");
gets(source);
printf("Enter the existing destination string : ");
gets(destination);
//Using strcpy library function//
strcpy(destination,source);
//Printing destination string//
printf("Destination string is : ");
puts(destination);
}輸出
執行上述程式後,它會產生以下結果 −
Enter the string to be copied : C programming Enter the existing destination string : bhanu Destination string is : C programming
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP