一、基本概念
字符串分割是指將一個完整的字符串按照指定的符號或者字符串進行拆分,得到若干個小的字符串。例如,將“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-hant/n/335107.html