2017-04-12 216 views
0

我一直在爭取這個問題一段時間,似乎無法找到一個簡單的解決方案,不涉及手工解析char *。我需要 '\ T' 分裂我的char *變量,我嘗試了以下幾種方式:C++:用' t'分隔符分隔char *

方法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 \ t檢驗' 結果在這樣的輸出:

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」'是單個字符的水平標籤。 – aschepler

回答

0

我會努力通過堅持std::函數使事情變得更簡單。 (p。你永遠不會使用這個: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; 
}