2011-12-09 18 views
11

可能な二重に配列に文字列:私は、データの入力ファイルがあり、各ラインはエントリーで
How to split a string in C++?スプリットC++

。各行で "field"は空白で区切られているので、スペースで区切る必要があります。他の言語はsplit(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として適格-名を使用します。

にstringstreamでそれを行うには。あなたのコードのどこかにusing namespace stdと書いてあるようですが、これは悪い習慣とみなされます。だから、それをしないでください。

+0

'using namespace x'を使うのが悪い習慣である理由についてのディスカッションへのリンクを提供できますか? – jli

+0

@jli:私の答えにリンクを追加しました。それを見てください。 – Nawaz

+2

@Nawazありがとう、私の他の質問を見て、私が使用している構文と私が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

もちろん、あなたが望むならばboostを使うこともできますし、ストリングストリームからコピーを行う別のSTL関数を使うこともできます。 – jli

+0

入力が空白で終わる場合、この内部whileループは最後に空のトークンを追加します。慣用的なC++ 'while(s >>トークン)'はそうではありません。 – Cubbi

+0

これは本当です。そのメソッドを使用するように編集することもできます。 – jli

3

strtokを試してみてください。それをC++リファレンスで探します:

+3

'strtok'はCライブラリのものですが、ポスターはC++で正しく行う方法を尋ねています。 – jli

+2

とC++はc?ではありません。以来、CライブラリはC++で動作を停止(または間違っている)? – LucianMLI

+0

それらを混在させると、不必要な依存を追加します。 – jli

3

私は私のsimlarの要件のための関数を書いています。 あなたはそれを使うことができるかもしれません!

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; 
}