2010-07-30 101 views

回答

0

你不能。 strtok的行为是用NUL字符替换分隔符。此行为不可配置。要返回每个子字符串(包括分隔符),必须找到strtok以外的函数,否则将strtok与您自己的一些处理结合起来。

2

你不能。 strtok通过将分隔符替换为'\ 0'来进行分割。如果不这样做,不会发生分裂。

然而,您可以创建一个像strtok这样的拆分类型的函数,但通过查找字符串应该拆分的位置以及(例如)分配存储空间并将字符复制到分隔符中。 strcspnstrpbrk可能会是一个有用的开始。

0

如果你的libc实现了它,看看strsep(3)

+0

文档http://kernel.org/doc/man-pages/online/pages/man3/strsep.3.html – Bklyn 2010-07-30 03:47:47

1

你可以使用boost吗? boost::algorithm::split完全符合你的要求。

你当然可以自己写一个;它不像分裂是复杂的:(注意:我没有真实地测试过)

std::wstring source(L"Test\nString"); 
std::vector<std::wstring> result; 
std::wstring::iterator start, end; 
start = source.begin(); 
end = std::find(source.begin(), source.end(), L'\n'); 
for(; end != source.end(); start = end, end = std::find(end, source.end(), L'\n')) 
    result.push_back(std::wstring(start, end)); 
result.push_back(std::wstring(start, end)); 
1

简单的不使用strtok。

使用C++流操作符。
getline()函数可以与定义线标记结束的额外参数一起使用。

#include <string> 
#include <sstream> 
#include <vector> 

int main() 
{ 
    std::string   text("This is text; split by; the semicolon; that we will split into bits."); 
    std::stringstream textstr(text); 

    std::string    line; 
    std::vector<std::string> data; 
    while(std::getline(textstr,line,';')) 
    { 
     data.push_back(line); 
    } 
} 

随着工作量的增加,我们甚至可以通过STL算法来支付他们的部分费用,我们只需要定义令牌如何流式传输。要做到这一点,只需定义一个令牌类(或结构),然后定义运算符>>,它可以读取令牌分隔符。

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

struct Token 
{ 
    std::string data; 
    operator std::string() const { return data;} 
}; 
std::istream& operator>>(std::istream& stream,Token& data) 
{ 
    return std::getline(stream,data.data,';'); 
} 

int main() 
{ 
    std::string   text("This is text; split by; the semicolon; that we will split into bits."); 
    std::stringstream textstr(text); 

    std::vector<std::string> data; 

    // This statement does the work of the loop from the last example. 
    std::copy(std::istream_iterator<Token>(textstr), 
       std::istream_iterator<Token>(), 
       std::back_inserter(data) 
      ); 

    // This just prints out the vector to the std::cout just to illustrate it worked. 
    std::copy(data.begin(),data.end(),std::ostream_iterator<std::string>(std::cout,"\n")); 
}