2017-04-12 219 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; 
}