2010-07-30 151 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")); 
}