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;
}

posted on 2014-06-20 09:47  xue泥娃娃  阅读(11293)  评论(0编辑  收藏  举报