Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

C program copy string โดยไม่ใช้ strcpy()


ในส่วนนี้เราจะดูวิธี copy string ไปอีก string โดยไม่ใช้ strcpy() function แก้ปัญหาได้ด้วยการเขียนฟังก์ชันเองเหมือน strcpy() แต่ที่นี่ใช้ trick ใช้ library function อื่น copy string

ตรรกะง่าย ใช้ sprintf() function พิมพ์ค่าเข้า string ไม่ใช่ console ความต่างกับ printf() คืออาร์กิวเมนต์แรกคือ string buffer ที่เก็บข้อมูล

Input − Take one string "Hello World" Output − It will copy that string into another string. "Hello World"

Algorithm

Step 1: Take a string Step 2: Create an empty string buffer to store result Step 3: Use sprintf() to copy the string Step 4: End

ตัวอย่างโค้ด

#include<stdio.h> main() {    char str[50]; //create an empty string to store another string    char *myString = "Program to copy a String"; sprintf(str, "%s", myString);//Use sprintf to copy string from myString to str printf("The String is: %s", str); }

Output:

The String is: Program to copy a String