使用多種方法編寫將兩個字符串連接在一起的程序-簡單


源程序:

第一種方法:

#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1="i am ";

  string str2="a teacher.";

  cout<<"連接前:"<<endl;

  cout<<"str1:"<<str1.data()<<endl;

  cout<<"str2:"<<str2.data()<<endl;

  str1.append(str2);

 

  cout<<endl;

  cout<<"連接后:";

  cout<<"str1:"<<str1.data()<<endl;

  cout<<"str2:"<<str2.data()<<endl;

   return 1;

}

 

 

第二種方法:

#include < iostream >

#include < string >

using namespace std;

void main()

{

  //使用string 類定義字符串,完成字符串連接

  string str1="C++",str2="程序設計";

  //string str1("C++"),str2("程序設計");

  string str3;

  str3 = str1+str2;//連接方式1

  cout<< str3<< endl;

  //使用char 數組定義字符串,完成連接

  char c1[] = {"c++"},c2[] = {"program"};

  char c3[20];

  int i=0,k=0;

  for(i=0;i<20;i++)//初始化c3

    c3[i]='\0';

  i=0;

  while(c1[i]!='\0')

  {

    c3[k]=c1[i];

    i++;

    k++;

  }

  i=0;

  while(c2[i]!='\0')

  {

    c3[k]=c2[i];

    i++;

    k++;

  }

  cout<< c3<< endl;

}

運行結果:

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM