C++學習(九)入門篇——String類
阿新 • • 發佈:2017-07-28
允許 res fort ngs 結果 初始化 ant content app
可以用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()
C++學習(九)入門篇——String類