使用 strcpy() 函式複製字串的 C 程式


在本部分中,我們將學習如何在不使用 strcpy() 函式的情況下,將一個字串複製到另一個字串。為了解決這個問題,我們可以編寫一個可以類似於 strcpy() 的函式,但這裡我們將使用其他一些技巧。我們將使用另一個庫函式來將一個字串複製到另一個字串。

邏輯非常簡單。這裡我們將使用 sprintf() 函式。此函式用於將某些值或行列印到字串中,但不是控制檯。這是 printf() 和 sprintf() 唯一不同的地方。以下第一個引數是字串緩衝區。在其中我們希望儲存我們的資料。

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

演算法

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);
}

輸出

The String is: Program to copy a String

更新時間: 30-Jul-2019

490 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.