一、基本概念
字元串分割是指將一個完整的字元串按照指定的符號或者字元串進行拆分,得到若干個小的字元串。例如,將「apple,banana,orange」按照逗號進行分割,可以得到三個小的字元串「apple」、「banana」和「orange」。
二、基本方法
實現字元串分割的方法有多種,包括使用C++的STL庫函數,使用C語言中的strtok()函數以及使用正則表達式等等。以下我們分別介紹。
1.使用STL庫函數
#include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; int main() { string str = "apple,banana,orange"; vector<string> vec; stringstream ss(str); string item; while (getline(ss, item, ',')) { vec.push_back(item); } for (int i = 0; i < vec.size(); i++) { cout << vec[i] << endl; } return 0; }
此方法利用了C++的STL庫函數中的stringstream,將字元串轉換成輸入流,再遍歷輸入流中的每一個字元串,並按照指定的符號進行分割。這種方法實現起來比較簡單,代碼可讀性也比較好,但是速度稍慢。
2.使用C語言中的strtok()函數
#include <iostream> #include <cstring> using namespace std; int main() { char str[] = "apple,banana,orange"; char *token = strtok(str, ","); while (token) { cout << token << endl; token = strtok(NULL, ","); } return 0; }
此方法利用了C語言中的strtok()函數,該函數可以按照指定的分隔符對字元串進行分割,並返回每個小字元串的指針。這種方法實現比較簡單,但是由於strtok()函數是使用靜態變數進行實現的,所以在多線程環境下會有線程不安全的問題。
3.使用正則表達式
#include <iostream> #include <regex> #include <string> using namespace std; int main() { string str = "apple,banana,orange"; regex pattern(","); sregex_token_iterator it(str.begin(), str.end(), pattern, -1); sregex_token_iterator end; while (it != end) { cout << *it << endl; it++; } return 0; }
此方法利用C++11中引入的正則表達式庫,通過編譯正則表達式來實現字元串分割,靈活性比較好。但是正則表達式的學習成本比較高,實現起來需要編寫比較複雜的正則模式。
三、常見問題
1.分割符號不唯一怎麼辦?
對於分割符號不唯一的情況,可以使用多個符號進行分割,並將得到的小字元串取交集。
2.分割出來的字元串中包含空格怎麼辦?
在使用STL庫函數或者正則表達式進行分割時,可以使用std::trim()函數去掉小字元串前後的空格。
3.分割出來的字元串中有換行符怎麼辦?
在使用C語言中的strtok()函數進行分割時,需要將換行符添加到分割符號中去,例如strtok(str, “,\n”)。
原創文章,作者:HBTVN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/335107.html