1. 程式人生 > 程式設計 >如何在c++中實現字串分割函式split詳解

如何在c++中實現字串分割函式split詳解

前言

在學習c++中string相關基本用法的時候,發現了sstream的istringstream[1]可以將字串類似於控制檯的方式進行輸入,而實質上這個行為等同於利用空格將一個字串進行了分割,於是考慮到可以利用這個特性來實現c++庫函式中沒有的字串分割函式split

string src("Avatar 123 5.2 Titanic K");
istringstream istrStream(src); //建立src到istrStream的聯絡
string s1,s2;
int n; double d; char c;
istrStream >> s1 >> n >> d >> s2 >> c;
//以空格為分界的各數值則輸入到了對應變數上

實現細節

目的是可以像js中一樣,呼叫一個函式即可以方便地獲取到處理完畢後的字串陣列,根據c++的實際情況再進行引數調整。

1. 輸入輸出:

string* split(int& length,string str,const char token = ' ')

返回:處理完的字串陣列的首地址

傳入:字串str、分隔符token(預設引數為空格)、以及引用引數length,指明處理完畢後動態分配的陣列長度

2. 資料透明處理:

由於istringstream會像cin一樣,把空格視為資料間的界限,所以當分隔符不是空格時,需要將傳入的分隔符換為空格,並且要提前對原有空格進行資料透明處理

字元替換利用了庫algorithm中的replace() [2]

 const char SPACE = 0;
 if(token!=' ') {
 // 先把原有的空格替換為ASCII中的不可見字元
 replace(str.begin(),str.end(),' ',SPACE); 
 // 再把分隔符換位空格,交給字串流處理
 replace(str.begin(),token,' ');
 }

假設輸入字串為:"a b,c,d,e,f g"
分隔符為非空格:','
則被替換為:"aSPACEb c d e fSPACEg"

3. 資料分割:

 //例項化一個字串輸入流,輸入引數即待處理字串
 istringstream i_stream(str); 
 //將length置零
 length = 0; 
 queue<string> q;
 //用一個string例項s接收輸入流傳入的資料,入隊並計數
 string s;
 while (i_stream>>s) {
 q.push(s);
 length++;
 }

4. 陣列生成:

 //根據計數結果動態開闢一個字串陣列空間
 string* results = new string[length]; 
 //將佇列中的資料轉入陣列中
 for (int i = 0; i < length; i++) {
 results[i] = q.front();
 //將替換掉的空格進行還原
 if(token!=' ') replace(results[i].begin(),results[i].end(),SPACE,' ');
 q.pop();
 }

完整程式碼

#include <iostream>
#include <string>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;

string* split(int& length,const char token = ' ') {
 const char SPACE = 0;
 if(token!=' ') {
 replace(str.begin(),SPACE);
 replace(str.begin(),' ');
 }
 istringstream i_stream(str);
 queue<string> q;
 length = 0;
 string s;
 while (i_stream>>s) {
 q.push(s);
 length++;
 }
 string* results = new string[length];
 for (int i = 0; i < length; i++) {
 results[i] = q.front();
 q.pop();
 if(token!=' ') replace(results[i].begin(),' ');
 }
 return results;
}

//測試:
int main() {
 int length;
 string* results = split(length,"a b,f g",',');
 for (int i = 0; i < length; i++) cout<<results[i]<<endl;
 return 0;
}

參考

[1] C++ string類(C++字串)完全攻略

[2] C++ string 替換指定字元

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。