IOS/ANSI C++98 标准通过添加string类扩展C++库因此现在可以string类型的变量而不是字符串数组来存储字符串,string类看起来很简单同时提供了字符串作为一种数据类型的表示方法。
下面请看一个小例子说明string对象和字符串数组之间的一些相同点和不同点
#include <iostream> #include <string> using namespace std; int main(){ char array1[20]; char array2[]={"jaguar"}; string str1; string str2 = "panther"; cout <<"输入:"<<endl; cin>>array1; cout <<"请输入一个字符串"<<endl; cin>>str1; cout <<array1<<" " <<array2<<" "<<str1<<" "<<str2<<endl; cout <<array2<<" "<<array2[2]<<endl; cout <<str2<<" "<<str2[2]<<endl; return 0; }
字符串对象直接赋值,或者字符串直接相加,但是字符数组是不能直接赋值的。
下面请查看例子:
#include <iostream> #include <string> using namespace std; int main(){ string s1 = "penguin"; string s2,s3; cout<<"将s1的值赋值给s2"<<endl; s2=s1; cout <<"s1=="<<s1<<" s2=="<<s2<<endl; cout <<"给s2赋值为buzzard"<<endl; s2="buzzard"; cout <<"s2::"<<s2<<endl; s3=s1+" "+s2; cout <<"字符串相加 s1+s2"<<endl; cout <<"s3=="<<s3<<endl; return 0; }