Translate

2009/08/26

用C++實作Strtok (類似 Java StringTokenizer)

來源:strtok:Split string into tokens

在網路上在查Strtok的做法,無意間找到C++的處理模式
有網友熱心的公佈出他的程式碼(類似 Java StringTokenizer)
內容寫的真的很棒,所以就轉來這邊收藏。
如果要套用AnsiString,則可以使用AnsiString的c_str()函式,也同樣適用哦!
以下是它的源始碼內容:
//---------------------------------------------------------------------------
#include <iostream>
#include <string>
#include <vector>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
using namespace std;

class StringTokenizer : public std::vector<string>{

public:
 StringTokenizer(const string& s, const string& delim = " ,") {
   string::size_type lastPos = s.find_first_not_of(delim, 0);
   string::size_type pos = s.find_first_of(delim, lastPos);

   while( string::npos != pos || string::npos != lastPos ) {
     push_back(s.substr(lastPos, pos - lastPos));
     lastPos = s.find_first_not_of(delim, pos);
     pos = s.find_first_of(delim, lastPos);
   }
 }
};
int main(int argc, char* argv[])
{
 StringTokenizer stk("1, 2, 3");

 for( StringTokenizer::size_type i = 0; i < stk.size(); i++ ) {
   cout << stk[i] << endl;
 }

 system("pause");
 return 0;
}
//---------------------------------------------------------------------------

沒有留言:

張貼留言

Delphi in Web Development: WebBroker + EasyUI (01)

I have been received many demand about web development for long time. But, I don't wont to use ASP.NET develop the web project. M...