編寫一程序,將兩個字符串連接起來的3種方法


1.用字符數組和自己書寫的函數實現

自己寫一個具有strcat函數功能的函數


實現代碼如下:

#include<iostream>
using namespace std;
int main(){
	char a[100],b[50];
	void Strcat(char a[],char b[]);
	cout<<"please input first string:"<<endl;
	cin>>a;
	cout<<"please input second string:"<<endl;
	cin>>b;
	Strcat(a,b);
	cout<<"The new string: "<<a;
	cout<<endl;
	return 0;	
}
void Strcat(char a[],char b[]){
	int i,j;
	for(i=0;a[i]!='\0';i++);
	cout<<"Length of first string:"<<i<<endl;
	for(j=0;b[j]!='\0';j++,i++){
		a[i]=b[j];
	}
	cout<<"Length of second string:"<<j<<endl;
}


2.用標准庫中的strcat函數

使用strlen()函數求數組的大小,strcat()函數用來連接字符串

實現代碼如下:
#include<iostream>
#include<string>
using namespace std;
int main(){
	char a[100],b[50];
	cout<<"please input first string:"<<endl;
	cin>>a;
	cout<<"please input second string:"<<endl;
	cin>>b;
	cout<<"Length of first string :"<<strlen(a)<<endl;
	cout<<"Length of first string :"<<strlen(b)<<endl;	
	cout<<"The new string: "<<strcat(a,b);
	cout<<endl;
	return 0;	
}


3.用string方法定義字符串變量

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a,b;
	cout<<"please input first string:"<<endl;
	cin>>a;
	cout<<"please input second string:"<<endl;
	cin>>b;
	cout<<"New string :"<<(a+b)<<endl;
	return 0;	
}



免責聲明!

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



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