ฟังก์ชันไลบรารี C char *strcpy(char *dest, const char *src) คัดลอกสตริงที่ชี้ไปโดย src ไปยัง ปลายทาง .
อาร์เรย์ของอักขระเรียกว่าสตริง
ประกาศ
ต่อไปนี้เป็นการประกาศสำหรับอาร์เรย์
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
รับด้านล่างเป็นโปรแกรม C แสดงให้เห็นถึงฟังก์ชั่นห้องสมุด strcpy -
โปรแกรม
#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