1.使用string类,必须在程序中包含头文件string。String类位于名称空间std中,所以必须提供一条using编译指令
2.不能将一个数组付给另一个数组,但可以将一个string对象赋给另一个string对象:
char charr1[20];//create an empty array
char charr2[20] = "jaguar";//create an initialized array
string str1;
string str2 = "panther";//create an initialized string
charr1 = charr2;//INVALID,no array assignment
str1 = str2;//VAILD,object assignment ok
3. string类简化了字符串合并操作。可以用运算符+将两个string对象合并起来,还可以使用运算符+=将字符串附加到string对象的末尾
string str3;
str3=str+str2;//assign str3 the joined-strings
str1+=str2;//add str2 to the end of str1
4. 函数strlen()是一个常规函数,接受一个C—风格字符串作为参数,并返回该字符串包含的字符数。函数size()的功能基本与此相同,但句法不同:str1不是被用做函数参数,而是位于函数名之前,他们之间用句点连接。这种句法表明,str1是一个对象,而size()是一个类方法。方法是一个函数,只能通过其所属类的对象进行调用。在这里,str1是一个string对象,而size()是string类的一个方法。总之,C函数用参数来指出要使用那个字符串,而C++类对象使用对象名和句点运算符来指出要使用哪个字符串。
int len1=str1.size()
int len2=strlen(charr1)
//line input
#include<iostream>
#include<string>//make string class available
#include<cstring>//C-style string library
int main() {
using namespace std;
char charr[20];
string str;
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);//indicate maximun length
cout << "you entered: " << charr << endl;
cout << "enter another line of text:\n";
getline(cin, str);//cin now an argument;no length specifier
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;
return 0;
}
/*//字符串合并
#include<iostream>
#include<string>
int main()
{
using namespace std;
string s1 = "penguin";
string s2, s3;
cout << "you can assign one string object to another:s2=s1\n ";
s2 = s1;
cout << "s1:" << s1 << ",s2:" << s2 << endl;
cout << "you can assign a C-style string to a string object.\n";
cout << "s2=\"buzzard\"\n";//转义符\"表示双引号
s2 = "buzzard";
cout << "s2:" << s2 << endl;
cout << "you can concatenate strings:s3=s1+s2\n";
s3 = s1 + s2;
cout << "s3: " << s3 << endl;
s1 += s2;
cout << "s1+=s2 yields s1= " << s1 << endl;
s2 += " for a day";
cout << "s2+= \" for a day\" yields s2= " << s2 << endl;
return 0;
}