要使用string类,必须在程序头文件中#include<string>,string类位于名称空间std中,必须提供一条using编译指令。
可以使用运算符 + 将两个string对象合并起来,还可以使用运算符 += 将字符串附加到string对象的末尾。
头文件cstring(以前为string.h)提供字符串的处理函数。
使用string对象的语法比使用C字符串函数更简单。String类具有自动调整大小的功能。
intlen1 = str1.seze();
intlen2 = strlen(charr1);
函数strlen()是一个常规函数,功能是字符串作为参数,返回字符数。函数size()的功能相同,不同之处是str1不是被用作函数参数,而是位于函数名之前,用句点连接。表明str1是一个string对象,而size()是一个类方法。总之,C函数使用参数来支出要使用哪个字符串,而C++ string类对象使用对象名和句点运算符来指出要使用哪个字符串。
#include <iostream>
#include <string>
#include <cstring>
int main()
{
usingnamespace std;
charcharr[20];
stringstr;
cout<< “Length of string in charr before input: ” << strlen(charr)<<endl;
cout<< “Length of string in str before input: ” << str.size() <<endl;
cout<< “Enter a line of text:\n”;
cin.getline(charr,20);
cout<< “You entered: ” << charr << endl;
cout<< “Enter another line of text:\n”;
getline(cin,str);
cout<< “You entered:” << str << endl;
cout<< “Length of string in charr after input: ” << strlen(charr)<< endl;
cout<< “Length of string in str after input: ” << str.size()<<endl;
return0;
}