【问题标题】:Split functionality for MFC Cstring ClassMFC Cstring 类的拆分功能
【发布时间】:2011-03-09 23:58:38
【问题描述】:

如何在 vc++ 中通过分隔符拆分 CString 对象?

例如我有一个string

“一+二+三+四”

转换为CString 变量。

【问题讨论】:

    标签: visual-c++ mfc


    【解决方案1】:
    CString sInput="one+two+three";
    CString sToken=_T("");
    int i = 0; // substring index to extract
    while (AfxExtractSubString(sToken, sInput, i,'+'))
    {   
       //.. 
       //work with sToken
       //..
       i++;
    }
    

    AfxExtractSubString on MSDN.

    【讨论】:

    • 这是糟糕的 OO 和糟糕的 API 的一个问题 - 功能无处不在 :) 很好的发现。
    • 您可以回答自己的问题。它在常见问题解答中。
    • 我会将逗号分隔符更改为加号,否则示例将无法运行。
    【解决方案2】:

    在 VC6 中,CString 没有 Tokenize 方法,你可以按照 strtok 函数和它的朋友。

    #include <tchar.h>
    
    // ...
    
    CString cstr = _T("one+two+three+four");
    TCHAR * str = (LPCTSTR)cstr;
    TCHAR * pch = _tcstok (str,_T("+"));
    while (pch != NULL)
    {
      // do something with token in pch
      // 
      pch = _tcstok (NULL, _T("+"));
    }
    
    // ...
    

    【讨论】:

    • TCHAR * str = (LPCTSTR)cstr 将抛出编译器错误a value of type "LPCTSTR" cannot be used to initialize an entity of type "TCHAR *"。你应该使用TCHAR * str = cstr.GetBuffer();
    【解决方案3】:
    int i = 0;
    CStringArray saItems;
    for(CString sItem = sFrom.Tokenize(" ",i); i >= 0; sItem = sFrom.Tokenize(" ",i))
    {
        saItems.Add( sItem );
    }
    

    【讨论】:

      【解决方案4】:

      类似于this question:

      CString str = _T("one+two+three+four");
      
      int nTokenPos = 0;
      CString strToken = str.Tokenize(_T("+"), nTokenPos);
      
      while (!strToken.IsEmpty())
      {
          // do something with strToken
          // ....
          strToken = str.Tokenize(_T("+"), nTokenPos);
      }
      

      【讨论】:

      • 您好,Tokenize 在 VC6 MFC 中不支持,但在 ATL 中支持
      • 您可能应该将该要求添加到问题中。
      • The docs for CStringT::Tokenize() 表示该函数会跳过前导分隔符,因此如果您真的想拆分字符串而不忽略空子字符串,那么我会说您不能使用Tokenize()。例如,“+一+二+三+四”不会产生 5 个子字符串的预期结果。
      猜你喜欢
      • 1970-01-01
      • 2010-11-04
      • 2019-10-19
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2011-12-01
      相关资源
      最近更新 更多