首先来看string字符串的使用:
int main()
{
string s1("wanghello");
string s2 = "helloworld";
string s3, s4, s5,s6;
s3 = s1 + s2;
s4 = s1 + "lili";
s5 = "lili" + s2;
s6="lili"+"hello";//error
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
return 0;
}
上面这两种对字符串的定义都是正确的,可以进行两个对象之间的相加,还可以对字符串和对象相加,对对象和字符串相加,这些操作都是可以完成的,也可以打印出来结果:
但是有一点要注意,编译器不支持对两个常性字符串相加。
实现字符串的+=操作:(字符串中没有-=这个操作)
int main()
{
string s1("lilil");
s1 += "hello";
cout << s1 << endl;
return 0;
}
string别的一些使用:
int main()
{
string s1("lilil");
string s2 = "helloworld";
int len = s1.size();//计算s1的长度
int size = s1.capacity();//计算s1的容量
for (int i = 0; i < len; i++)//访问字符串中的单个字符
{
cout << s1[i] << " ";
}
cout << endl;
s1[0] = 'x';//修改字符串中的字符
cout << s1 << endl;
const char* s = s1.c_str();//获得s1这个对象中的字符串的地址
s1.append("hello");//追加字符串
cout << s1 << endl;
cout << (s1 == s2) << endl;//比较两个字符串的大小
cout << (s1 > s2) << endl;
cout << (s1 < s2) << endl;
return 0;
}
注意在使用这些之前要加string这个库:
#include <string>