C++ 字符串 4-- 18.13~15.string型字符串的合并、连接

#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
     18-13 18.13~15.string型字符串的合并、连接
  1) string类的字符串的长度是自动变长的
---------------------------------*/
int main()
{
cout<<"------strcat------------:"<<endl;
char ch1[50]="what's your name ?"; 
char ch2[]="My name is Jack.";
cout<<ch1<<endl<<ch2<<endl;
strcat(ch1,ch2);       //连接字符串
cout<<ch1<<endl<<ch2<<endl;


cout<<"------strncat------------:"<<endl;
strcpy(ch1,"what's your name ?"); 
strcpy(ch2,"My name is Jack.");
cout<<ch1<<endl<<ch2<<endl;
strncat(ch1,ch2,5);  //strncat()将字符串ch2的头5个字符连接到字符串ch1
cout<<ch1<<endl<<ch2<<endl;


cout<<"-------str1+str2-----------:"<<endl;
string str1="what's your name ?"; 
string str2="My name is Jack.";
str1=str1+str2;   //C++的string类重载了“+”
cout<<str1<<endl<<str2<<endl;
cout<<"strlen(str2)="<<strlen(str2.c_str())<<endl;//c_str()将C++字符串转换为C的类型
cout<<"size(str2)="<<str2.size()<<endl; //效果跟strlen一样,就是计算'\0'之前共有多少个字符


cout<<"-------append-----------:"<<endl;
str1="what's your name ?"; 
str2="My name is Jack.";
cout<<str1<<endl<<str2<<endl;
str1.append(str2,1,3);    //append()将str2的脚标1开始的连续3个字符追加到str1
cout<<str1<<endl<<str2<<endl;


cout<<"----size-----length---------:"<<endl;
string str3; //size()和length()的使用效果一样;未赋初值的string类的对象,长度为零
cout<<"size(str3)="<<str3.size()<<endl;    //size()是后期版本string类中成员
cout<<"length(str3)="<<str3.length()<<endl;//length()是早期版本string类中成员


return 0;

}

运行结果:

------strcat------------:
what's your name ?
My name is Jack.
what's your name ?My name is Jack.
My name is Jack.
------strncat------------:
what's your name ?
My name is Jack.
what's your name ?My na
My name is Jack.
-------str1+str2-----------:
what's your name ?My name is Jack.
My name is Jack.
strlen(str2)=16
size(str2)=16
-------append-----------:
what's your name ?
My name is Jack.
what's your name ?y n
My name is Jack.
----size-----length---------:
size(str3)=0
length(str3)=0
Press any key to continue

猜你喜欢

转载自blog.csdn.net/paulliam/article/details/80515819