一、使用string數組存儲文本數據
在C++中,可以使用string類型的數組來存儲文本數據。
#include <iostream> #include <string> using namespace std; int main() { const int SIZE = 5; string texts[SIZE]; for(int i=0; i<SIZE; i++) { cout << "請輸入第" << i+1 << "個字元串: "; cin >> texts[i]; } cout << "你輸入的字元串為: " << endl; for(int i=0; i<SIZE; i++) { cout << texts[i] << endl; } return 0; }
上述代碼中,定義了一個長度為5的string數組,循環讀取用戶輸入的字元串並存儲到數組中,最後循環輸出存儲的字元串。
二、使用string類的成員函數操作字元串
除了使用數組存儲字元串,C++中的string類還提供了豐富的成員函數來操作字元串。
1. size()
size()函數返回字元串的長度。
#include <iostream> #include <string> using namespace std; int main() { string text = "Hello world!"; cout << "字元串的長度為: " << text.size() << endl; return 0; }
2. substr()
substr()函數可以截取字元串的一部分。
#include <iostream> #include <string> using namespace std; int main() { string text = "Hello world!"; string subtext = text.substr(0, 5); cout << "截取的字元串為: " << subtext << endl; return 0; }
3. append()
append()函數可以在字元串的末尾添加一個字元串。
#include <iostream> #include <string> using namespace std; int main() { string text = "Hello "; text.append("world!"); cout << "拼接後的字元串為: " << text << endl; return 0; }
4. replace()
replace()函數可以替換字元串的一部分。
#include <iostream> #include <string> using namespace std; int main() { string text = "Hello world!"; text.replace(6, 5, "there"); cout << "替換後的字元串為: " << text << endl; return 0; }
三、使用STL演算法操作string數組
C++ STL中的演算法庫可以方便地對string數組進行排序、查找等操作。
1. sort()
sort()函數可以對string數組進行升序排序。
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { const int SIZE = 5; string texts[SIZE] = {"apple", "banana", "orange", "grape", "pear"}; sort(texts, texts+SIZE); cout << "排序後的字元串為: " << endl; for(int i=0; i<SIZE; i++) { cout << texts[i] << endl; } return 0; }
2. find()
find()函數可以在string數組中查找指定字元串。
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { const int SIZE = 5; string texts[SIZE] = {"apple", "banana", "orange", "grape", "pear"}; string str = "banana"; if(find(texts, texts+SIZE, str) != texts+SIZE) { cout << "找到了字元串 " << str << endl; } else { cout << "沒找到字元串 " << str << endl; } return 0; }
3. count()
count()函數可以計算string數組中指定字元串出現的次數。
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { const int SIZE = 5; string texts[SIZE] = {"apple", "banana", "orange", "banana", "pear"}; string str = "banana"; int count = 0; for(int i=0; i<SIZE; i++) { if(texts[i] == str) { count++; } } cout << "字元串 " << str << " 出現了 " << count << " 次" << endl; return 0; }
四、總結
使用C++ string數組存儲和操作文本數據,可以通過使用string類型的數組存儲文本數據,使用string類的成員函數操作字元串,以及使用STL演算法操作string數組等方式來實現。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/286133.html