标签:入门 nts alt yield 返回 对象 assign stream ast
可以用string类而不是字符数组来存储字符串,string更加简单
要是用string类,则要在程序中包含头文件string,且位于std名称空间中,string类隐藏了字符串的数组性质,可以像处理普通变量那样处理字符串
程序清单4.7 strtype1.cpp //strtypel.cpp - - using the C++ string class #include<iostream> #include<string> int main() { using namespace std; char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; cout << "Enter a kind of feline: "; cin >> charr1; cout << "Enter another kind of feline: "; cin >> str1; cin.get(); cout << "Here are some felines:\n"; cout << charr1 << " " << charr2 << " " << str1 << " " << str2 << endl; cout << "The third letter in " << charr2 << " is " << charr2[2] << endl; cout << "The third letter in " << str2 << " is " << str2[2] << endl; cin.get(); }
输出结果:
string对象声明为简单变量
char数组为一组用于存储字符串的char存储单元,string类为一个存储字符串的实体
除了数组初始化可用列表初始化,也适用于字符串初始化
char first_date[ ] ={"Le Chapon Dodu"};
string second_date={"Le Chapon Dodu"};
char third_date[ ] {"Le Chapon Dodu"};
string forth_date {"Le Chapon Dodu"};
不能将一个数组赋给另一个数组,但可以将一个string对象赋给另一个string对象
char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; charr1=charr2; //不允许这么做 str1=str2; //可以
string类简化了字符串合并操作
还可以将两个string对象合并起来
string str3; str3 = str1+str2; str1+=str2;
程序清单4.8 strtype2.cpp //strtype2.cpp - - assigning,adding,and appending #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 = s2 + s1\n"; s3 = s2 + s1; cout << "s3:" << s3 << endl; cout << "You can append strings.\n"; s1 += s2; cout << "s1 += s2 yields s1 = " << s1 << endl; s2 += " for a day"; cout << "s2 += \"for a day\" yields s2 = " << s2 << endl; cin.get(); }
结果:
在C++新增string类前,还是要完成给字符串赋值,用头文件cstring中的函数来完成,用函数strcpy()将字符串复制到字符数组中,用strcat()将字符串附加到字符数组末尾
strcpy(charr1,charr2); //copy charr2 to charr1 strcat(charr1,charr2); //append contents of charr2 to charr1
程序清单4.9 strtype3.cpp //strtype3.cpp - - more string class features #include<iostream> #include<string> #include<cstring> int main() { using namespace std; char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; str1 = str2; strcpy_s(charr1,charr2); str1 += " paste"; strcat_s(charr1, " juice"); int len1 = str1.size(); int len2 = strlen(charr1); cout << "The string " << str1 << " contains " << len1 << " characters.\n"; cout << "The string " << charr1 << " contains " << len2 << " characters.\n"; cin.get(); }
输出:
函数strlen()是一个常规函数,返回该字符串包含的字符数。
str1是一个对象,而size()是一个类对象,所以这样调用str1.size()
标签:入门 nts alt yield 返回 对象 assign stream ast
原文地址:http://www.cnblogs.com/daisyliar/p/7248975.html