C++ 程式複製字串


字串是一個一維字元陣列,以一個空字元結尾。一個字串的值可以複製到另一個字串中。這可以使用標準庫函式 strcpy() 函式或不用它來完成。

不用 strcpy() 函式複製字串的程式如下所示:

示例

 即時演示

#include <iostream>
using namespace std;
int main() {
   char str1[100] = "Magic";
   char str2[100];
   int i;
   for(i = 0; str1[i] != '\0'; i++)
   str2[i] = str1[i];
   str2[i] = '\0';
   cout<<"The contents of str2 are: "<<str2;
   return 0;
}

輸出

The contents of str2 are: Magic

在上面的程式中,使用了一個 for 迴圈將 str1 的內容複製到 str2 中。此迴圈從 str1 中的 0 執行到空字元。在 for 迴圈之後,在 str2 中的字串末尾新增空字元並顯示它。這顯示如下。

for(i = 0; str1[i] != '\0'; i++)
str2[i] = str1[i];
str2[i] = '\0';
cout<<"The contents of str2 are: "<<str2;

使用 strcpy() 函式複製字串的程式如下所示。

示例

 即時演示

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[100] = "Magic";
   char str2[100];
   strcpy(str2,str1);
   cout<<"The contents of str2 are: "<<str2;
   return 0;
}

輸出

The contents of str2 are: Magic

在上面的程式中,使用 strcpy() 函式將 str1 的內容複製到 str2 中。然後顯示 str2 的內容。這在下面的程式碼片段中展示。

strcpy(str2,str1);
cout<<"The contents of str2 are: "<<str2;

更新於:24-Jun-2020

4K+ 瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.