(和C语言比起来 还是要方便很多)
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string str1,str2;
cout<<"请输入两个字符串"<<endl;
cin>>str1>>str2;
cout<<"判断两个字符串是否相等"<<endl;
if(str1==str2) {cout<<"Yes"<<endl;}
else cout<<"No"<<endl;
cout<<"将两个字符串连接一起"<<endl;
string str3=str1+str2;
cout<<str3<<endl;
cout<<"将字符串1复制到字符串2里面去"<<endl;
str2=str1;
cout<<str2<<endl;
cout<<"将字符串1尾部加几个字母"<<endl;
str1+="hello";
cout<<str1<<endl;
cout<<"统计字符串1的长度"<<endl;
cout<<str1.size()<<endl;
return 0;
}
使用构造方法
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
//构造方法
string str("bizhaniubi"); //赋值
cout<<"str:"<<str<<endl;
string str1(20,'$');//赋值20个$
cout<<"str1:"<<str1<<endl;
string str2(str1);
cout<<"str2:"<<str2<<endl;
char str3[100]={"12345678910111213141516171819"};
cout<<"str3:"<<str3<<endl;
string str4(str3,5);//去数组前5个字符
cout<<"str4:"<<str4<<endl;
string str5(str3,5,10);//从当前数组第5个字符开始去10个字符;
cout<<"str5:"<<str5<<endl;
string str6(&str3[3],&str3[9]);//取当前地址符第3个到第9个赋值给str6
//使用的区间是前闭后开 【 n,m )
cout<<"str6:"<<str6<<endl;
return 0;
}