一、前言
int,float,char,C++標准庫提供的類型:string,vector。
string:可變長字符串的處理;vector一種集合或者容器的概念。
二、string類型簡介
C++標准庫中的類型,代表一個可變長的字符串
char str[100] = “I Love China”; // C語言用法
三、定義和初始化string對象
#include <iostream> #include <string> using namespace std; int main() { string s1; // 默認初始化,s1=””,””空串,表示里面沒有字符 string s2 = “I Love China”; // 把I Love China 這個字符串內容拷貝到了s2代表的一段內存中,拷貝時不包括末尾的\0; string s3(“I Love China”); // 與s2的效果一樣。 string s4 = s2; // 將s2中的內容拷貝到s4所代表的的一段內存中。 int num = 6; string s5 = (num,’a’);// 將s5初始化為連續num個字符的’a’,組成的字符串,這種方式不太推薦,因為會在系統內部創建臨時對象。 return 0; }
四、string對象上的操作
(1)判斷是否為空empty(),返回的布爾值
string s1; if(s1.empty()) // 成立 { cout << “s1字符串為空” <<endl; }
(2)size()/length():返回字節/字符數量,代表該字符串的長度。unsigned int
string s1; cout << s1.size() << endl; // 0 cout << s1.length() << endl; // 0 string s2 = “我愛中國”; cout << s2.size() << endl;// 8 cout << s2.length() << endl; // 8 string s3 = “I Love China”; cout << s3.size() << endl;// 12 cout << s3.length() << endl; // 12
(3)s[n]:返回s中的第n個字符,(n是個整型值),n代表的是一個位置,位置從0開始,到size()-1;
如果用下標n超過這個范圍的內容,或者本來是一個空字符串,你用s[n]去訪問,都會產生不可預測的作用。
string s3 = “I Love China”; if(s3.size()>4) { cout << s3[4] << endl; s3[4] = ‘2’; } cout << s3 << endl; // I Lowe China
(4)s1+s2:字符串的連接,返回連接之后結果,其實就是得到一個新的string對象。
string s4 = “abcd”; string s5 = “efgk” string s6 = s4 + s5; cout << s6 <<endl;
(5)s1 = s2:字符串對象賦值,用s2中的內容取代s1中的內容
string s4 = “abcd”; string s5 = “efgk” s5 = s4; cout << s5 <<endl; // abcd
(6)s1 == s2:判斷兩個字符串是否相等。大小寫敏感:也就是大小寫字符跟小寫字符是兩個不同的字符。相等:長度相同,字符全相同。
string s4 = “abcd”; string s5 = “abcd” if(s5 == s4) { cout << “s4 == s5” <<endl; // abcd }
(7)s1 != s2:判斷兩個字符串是否不相等
string s4 = “abcd”; string s5 = “abcD” if(s5 != s4) { cout << “s4 != s5” <<endl; // abcd }
(8)s.c_str():返回一個字符串s中的內容指針,返回一個指向正規C字符串的指針常亮,也就是以\0存儲。
這個函數的引入是為了與C語言兼容,在C語言中沒有string類型,所以我們需要通過string對象的c_str()成員函數將string對象轉換為C語言的字符串樣式。
string s4 = “abcd”; const char *p = s4.c_str(); // abcd char str[100]; strcpy_s(str,sizeof(str),p); cout << str << endl; string s11(str); // 用C語言的字符串數組初始化string類型。
(9)讀寫string對象
string s1; cin >> s1; // 從鍵盤輸入 cout << s1 << endl;
(10)字面值和string相加
string str1 = “abc”; string str2 = “def”; string str3 = s1 + “ and ” + s2 + ‘e’; // 隱式類型轉換 cout << str3 << endl; // abc and defe;
// string s1 = “abc” + “def”; // 語法上不允許
(11)范圍for針對string的使用:C++11提供了范圍for:能夠遍歷一個序列的每一個元素。string可以看成一個字符序列。
string s1 = “I Love China”; for(auto c:s1) // auto:變量類型自動推斷 { cout << c << endl; // 每次輸出一個字符,換行 } for(auto &c:s1) // auto:變量類型自動推斷 { // toupper()把小寫字符轉換為大寫,大寫字符不變 c = toupper(c); // 因為c是一個引用,所以這相當於改變s1中的值 } cout << s1 << endl;