Tokenize()和_tcstok()都是用來分割字符串的方法。但是其各自的使用還是有很多不同。
下面對字符串“%s111gdfafd%s\t023232%s\t1%s\t2%s\t3%s\t4%s\t0XFF0000%s\tfdas”用這兩個函數都進行一些相同匹配分割處理,代碼和結果對比如下:
Tokenize():
#include "stdafx.h" #pragma once #include <stdio.h> #include <tchar.h> #include <vector> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 構造函數將是顯式的 #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // 從 Windows 頭中排除極少使用的資料 #endif #include <afx.h> #include <afxwin.h> // MFC 核心組件和標准組件 #include <iostream>//函數功能:按指定長度截取字符串前面的部分 int _tmain(int argc, _TCHAR* argv[], TCHAR* envp[]) { CString sBuf=_T(" %s111gdfafd%s\t023232%s\t1%s\t2%s\t3%s\t4%s\t0XFF0000%s\tfdac"); CString Seperator = _T("1%s\t"); int Position = 0; CString Token; Token = sBuf.Tokenize(Seperator, Position); while(!Token.IsEmpty()) { // Get next token. Token = sBuf.Tokenize(Seperator, Position);//從iStart位置取出字符串中含pszTokens分割符間的內容; TCHAR* szTrunc = new TCHAR[Token.GetLength() + 1];//將結果保存在堆里 _tcscpy(szTrunc,Token);//結果拷貝 std::wcout<<szTrunc<<std::endl; if (_tcslen(szTrunc) > 0) { delete [] szTrunc; } } system("pause"); return 0; }
_tcstok():
#include "stdafx.h" #pragma once #include <stdio.h> #include <tchar.h> #include <vector> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 構造函數將是顯式的 #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // 從 Windows 頭中排除極少使用的資料 #endif #include <afx.h> #include <afxwin.h> // MFC 核心組件和標准組件 #include <iostream>//函數功能:按指定長度截取字符串前面的部分 int _tmain(int argc, _TCHAR* argv[], TCHAR* envp[]) { CString str = _T("%s111gdfafd%s\t023232%s\t1%s\t2%s\t3%s\t4%s\t0XFF0000%s\tfdas"); TCHAR seps[] = _T("1%s\t"); TCHAR* token = _tcstok( str.GetBuffer(), seps ); while( token != NULL ) { //MessageBox( token, token, MB_OK ); //MessageBox(_T("dfzdsas")); std::wcout<<token<<std::endl; token = _tcstok( NULL, seps );//這一句刪去會導致無限循環 } system("pause"); return 0; }