# 第十二周 字串處理 標頭檔 string.h 宣告許多字串 (string) 處理相關的函數 (function) ,包括拷貝、相接、搜尋、測試相等、計算長度等。 以 str 起頭的函數作為處理字串之用,另有以 mem 起頭的函數,這些函數則可以進行記憶體區塊的操 ## 練習 ### 說明: 練習string 類別的字串處理函式:ㄅCstr()、append()、substr()、compare()、copy () find()、find_ first _not_of()、find first_ of()~insert()、replace()、rfind( 、swap() ```cpp= #include <iostream> #include <cstring> using namespace std; int main() { string str1 = "123"; string str2 = "456"; string str3; char cstr[10]; int pos; sprintf_s(cstr, str1.c_str()); str3 = cstr; //取出字元,與str1[2]相同 cout << "取出索引位置2的字元:" << str1.at(2) << endl; //字串相加、附加。 str3 = str1 + str2; str3.append("abc123"); cout << "str3= " << str3 << endl; //取子字串 cout << "取子字串= " << str3.substr(4, 3) << endl; //比較字串 str2 = "456789"; cout << "字串比較= " << str3.compare(3, 3, str2.c_str(), 3) << endl; //複製字串 strcpy_s(cstr, "hello"); str3.copy(cstr, 3, 6); cout << "字元陣列字串cstr= " << cstr << endl; //移除子字串 cout << "移除子字串: " << str3.erase(0, 3) << endl; //尋找:在"abc123"中尋找2個字元"ab" pos = str3.find("abd", 3, 2); cout << "尋找的索引位置= " << pos << endl; //str3的"56abc"在"465ba"中並沒有c,所以回傳c在str3的索引位置 str2 = "465ba12c"; pos = str3.find_first_not_of(str2.c_str(), 1, 5); cout << "第一個沒出現的字元:" << str3[pos] << endl; //尋找第一個出現的字元 str2 = "5ba6"; //"6ba5" pos = str3.find_first_of(str2.c_str(), 2, 3); cout << "第一個出現的字元:" << str3[pos] << endl; //插入字串 cout << "str3= " << str3.insert(0, "hello123", 5) << endl; //字串取代 str2 = "apple"; str3.replace(0, 3, str2, 1, 3); cout << "str3= " << str3 << endl; //尋找最後出現的字元 pos = str3.rfind("lb", 10, 1); cout << "尋找最後出現的字元的索引位置: " << pos << endl; //字串交換 str3.swap(str1); cout << "字串交換後:"; cout << "str1= " << str1 << ", str3= " << str3 << endl; system("pause"); }