2011-12-09 65 views
11

可能重複:
How to split a string in C++?分割字符串轉換成C中的陣列++

我有數據的輸入文件,並且每個行是一個條目。在每一行中,每個「字段」由一個空格「」隔開,所以我需要按空格分隔行。其他語言有一個稱爲分裂(C#,PHP等)的功能,但我無法找到一個用於C++。我怎樣才能做到這一點?這裏是我的代碼得到的行:

string line; 
ifstream in(file); 

while(getline(in, line)){ 

    // Here I would like to split each line and put them into an array 

} 

回答

20
#include <sstream> //for std::istringstream 
#include <iterator> //for std::istream_iterator 
#include <vector> //for std::vector 

while(std::getline(in, line)) 
{ 
    std::istringstream ss(line); 
    std::istream_iterator<std::string> begin(ss), end; 

    //putting all the tokens in the vector 
    std::vector<std::string> arrayTokens(begin, end); 

    //arrayTokens is containing all the tokens - use it! 
} 

順便說一句,使用合格的,名稱,如std::getlinestd::ifstream像我一樣。看起來你寫了using namespace std在你的代碼中被認爲是不好的做法。所以,不要做:

+0

你能否提供一個鏈接來討論爲什麼使用'using namespace x'是不好的做法? – jli

+0

@jli:添加了鏈接到我的答案。看見。 – Nawaz

+2

@Nawaz謝謝,看看我的其他問題,我正在使用的語法以及我從uni的教師那裏學習C++的方式非常可疑:S !!!!! –

0

無論是從您的ifstream使用stringstream或閱讀令牌通過令牌。

要與字符串流做到這一點:

string line, token; 
ifstream in(file); 

while(getline(in, line)) 
{ 
    stringstream s(line); 
    while (s >> token) 
    { 
     // save token to your array by value 
    } 
} 
+0

當然,如果您願意,或者其他STL函數可以使用boost來複製出stringstream,那麼可以使用boost。 – jli

+0

如果輸入以空白結尾,則此內部while循環會在最後生成一個附加的空令牌。慣用的C++'while(s >> token)'不。 – Cubbi

+0

這是真的。也可以編輯以使用該方法。 – jli

3

嘗試strtok。在C++參考中查找它:

+3

'strtok'是一個C庫的東西,而海報正在問如何用C++正確地做到這一點。 – jli

+2

和C++不是c?(...... OMG所有這些年來他們都對我撒謊:D)。因爲當C庫已經停止在C++中工作(或轉向不正確)? – LucianMLI

+0

如果混合使用,則會增加不必要的依賴性等問題。 – jli

3

我寫了一個函數來模擬我的需求。 可能是你可以使用它!

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) 
{ 
    std::stringstream ss(s+' '); 
    std::string item; 
    while(std::getline(ss, item, delim)) 
    { 
     elems.push_back(item); 
    } 
    return elems; 
} 
1

下面的代碼使用strtok()分割一個字符串轉換成令牌和在載體中存儲該令牌。

#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <string> 

using namespace std; 


char one_line_string[] = "hello hi how are you nice weather we are having ok then bye"; 
char seps[] = " ,\t\n"; 
char *token; 



int main() 
{ 
    vector<string> vec_String_Lines; 
    token = strtok(one_line_string, seps); 

    cout << "Extracting and storing data in a vector..\n\n\n"; 

    while(token != NULL) 
    { 
     vec_String_Lines.push_back(token); 
     token = strtok(NULL, seps); 
    } 
    cout << "Displaying end result in vector line storage..\n\n"; 

    for (int i = 0; i < vec_String_Lines.size(); ++i) 
    cout << vec_String_Lines[i] << "\n"; 
    cout << "\n\n\n"; 


return 0; 
}