1. 程式人生 > >C++程序設計入門(上) string類的基本用法

C++程序設計入門(上) string類的基本用法

ans append compare 註意 emp ras (上) ase become

?string類中的函數

1. 構造

2. 追加

3. 賦值

4. 位置與清除

5. 長度與容量

6. 比較

7. 子串

8. 搜索

9. 運算符

追加字符串

string s1("Welcome");
s1.append(" to C++"); // appends " to C++" to s1 
cout << s1 << endl; // s1 now becomes Welcome to C++

string s2("Welcome");
s2.append(" to C and C++", 3, 2); // appends " C" to s2 
cout << s2 << endl; // s2 now becomes Welcome C string s3("Welcome"); s3.append(" to C and C++", 5); // appends " to C" to s3 cout << s3 << endl; // s3 now becomes Welcome to C string s4("Welcome"); s4.append(4, G); // appends "GGGG" to s4 cout << s4 << endl; //
s4 now becomes WelcomeGGGG

為字符串賦值

string s1("Welcome"); 
s1.assign("Dallas"); // assigns "Dallas" to s1 
cout << s1 << endl; // s1 now becomes Dallas

string s2("Welcome"); 
s2.assign("Dallas, Texas", 1, 3); // assigns "all" to s2 
cout << s2 << endl; // s2 now becomes all
string s3("Welcome"); s3.assign("Dallas, Texas", 6); // assigns "Dallas" to s3 cout << s3 << endl; // s3 now becomes Dallas string s4("Welcome"); s4.assign(4, G); // assigns "GGGG" to s4 cout << s4 << endl; // s4 now becomes GGGG

?at(index): 返回當前字符串中index位置的字符

?clear(): 清空字符串

?erase(index, n): 刪除字符串從index開始的n個字符

?empty(): 檢測字符串是否為

string s1("Welcome");
cout << s1.at(3) << endl; // s1.at(3) returns c
cout << s1.erase(2, 3) << endl; // s1 is now Weme


s1.clear(); // s1 is now empty
cout << s1.empty() << endl; // s1.empty returns 1 (means true)

比較字符串:

string s1("Welcome");
 string s2("Welcomg");

cout << s1.compare(s2) << endl; // returns -2 
cout << s2.compare(s1) << endl; // returns 2
cout << s1.compare("Welcome") << endl; // returns 0

獲取子串:

at() 函數用於獲取一個單獨的字符;而substr() 函數則可以獲取一個子串

string s1("Welcome");
cout << s1.substr(0, 1) << endl; // returns W ; 從 0 號位置開始的 1 個字符
cout << s1.substr(3) << endl; // returns come ; 從 3 號位置直到末尾的子串
cout << s1.substr(3, 3) << endl; // returns com ;從 3 號位置開始的 3 個字符

搜索字符串

string s1("Welcome to HTML"
cout << s1.find("co") << endl; // returns 3 ; 返回子串出現的第一個位置); 
cout << s1.find("co", 6) << endl; // returns -1 從 6 號位置開始查找子串出現的第一個位置 
cout << s1.find(o) << endl; // returns 4    返回字符出現的第一個位置 
cout << s1.find(o, 6) << endl; // returns 9   從 6 號位置開始查找字符出現的第一個位置

插入和替換字符串

?insert() : 將某個字符/字符串插入到當前字符串的某個位置

?replace() 將本字串從某個位置開始的一些字符替換為其它內容

string s1("Welcome to HTML"); 
s1.insert(11, "C++ and "); 
cout << s1 << endl; // s1 becomes Welcome to C++ and HTML

string s2("AA"); 
s2.insert(1, 4, B); // 在 1 號位置處連續插入 4 個相同字符 
cout << s2 << endl; // s2 becomes to ABBBBA

string s3("Welcome to HTML"); 
s3.replace(11, 4, "C++"); // 從 11 號位置開始向後的 4 個字符替換掉。註意 ‘\0‘ 
cout << s3 << endl; // returns Welcome to C++

C++程序設計入門(上) string類的基本用法