2017-04-12 3 views
0

私は今この問題に取り組んできましたが、手でchar *を解析することを含まない単純な解決策を見つけることはできませんでした。私は、 '\ tの' で私のchar *変数を分割する必要がある、と私は、次の方法試してみた:C++:char *を ' t'デリミタで区切る

方法1:

char *splitentry; 
    std::string ss; 

    splitentry = strtok(read_msg_.data(), "\\t"); 
    while(splitentry != NULL) 
    { 
    std::cout << splitentry << std::endl; 
    splitentry = strtok(NULL, "\\t"); 
    } 

't検定\ TA tthis \ TIS \ \' 入力を使用しますこの出力で 結果:

his 
is 
a 
es 

方法2:

std::string s(read_msg_.data()); 

boost::algorithm::split(strs, s, boost::is_any_of("\\t"); 
for (int i = 0; i < strs.size(); i++) 
    std::cout << strs.at(i) << std::endl; 

同じ出力を生成します。 私はboost :: split_regexを使ってみましたが、正規表現の値として "\\ t"を使用しましたが、何も分割されません。私はそれを私自身で分割しなければならないのですか?これについて間違っていますか?

+3

' "\\ tが"' 2つの文字のバックスラッシュとtです。 '" \ t "'は1文字の水平タブです。 – aschepler

答えて

0

私は、std::の機能に固執することで少し簡単にしようとします。 (あなたはこれを絶対に使用しません:std::string ss;

なぜこんなことをしないのですか?

方法1:std::istringstream

std::istringstream ss(read_msg_.data()); 
std::string line; 
while(std::getline(ss,line,ss.widen('\t'))) 
    std::cout << line << std::endl; 

方法2:std::string::substr(私の好ましい方法は、それが軽量であるように)

std::string data(read_msg_.data()); 
std::size_t SPLITSTART(0); // signifies the start of the cell 
std::size_t SPLITEND(0); // signifies the end of the cell 
while(SPLITEND != std::string::npos) { 
    SPLITEND = data.find('\t',SPLITSTART); 
    // SPLITEND-SPLITSTART signifies the size of the string 
    std::cout << data.substr(SPLITSTART,SPLITEND-SPLITSTART) << std::endl; 
    SPLITSTART = SPLITEND+1; 
} 
関連する問題