【问题标题】:C - Split TCHARC - 拆分 TCHAR
【发布时间】:2016-09-10 23:18:35
【问题描述】:

如何将TCHAR 拆分为其他变量? 示例:

TCHAR comando[50], arg1[50], arg2[50];
Mensagem msg;
_tcscpy(msg.texto, TEXT("MOVE 10 12"));

所以,msg.texto 有字符串“MOVE 10 12”,我希望变量 comando[50] 为“MOVE”,变量 arg1 为“10”,变量 arg2 为“12” ”。我怎样才能做到这一点? 抱歉有些可能的英语错误。 提前致谢!

已解决:

TCHAR *pch;
    pch = _wcstok(msg.texto, " ");
        _tcscpy(comando, pch);
        pch = _wcstok(NULL, " ");
        _tcscpy(arg1, pch);
        pch = _wcstok(NULL, " ");
        _tcscpy(arg2, pch);

【问题讨论】:

标签: c string split scanf tchar


【解决方案1】:

要使用不可知的版本,您应该使用_tcstok

【讨论】:

    【解决方案2】:

    对于TCHAR,您可以使用strtok,如下例所示:

    #include <stdio.h>
    #include <string.h>
    
    typedef char TCHAR;
    
    int main ()
    {
      TCHAR str[] ="MOVE 10 12";
      TCHAR * pch;
      printf ("Splitting string \"%s\" into tokens:\n",str);
      pch = strtok (str," ");
      while (pch != NULL)
      {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ");
      }
      return 0;
    }
    

    如果是wchar_t,则可以使用wcstok()

    wchar_t *wcstok( wchar_t *strToken, const wchar_t *strDelimit );

    【讨论】:

    • 我记得,TCHAR 可能是charwchar_t——更常见的是后者。 strtok 不适用于 wchar_t 的数组。 (不记得有没有对应的函数对宽字符串进行操作。)
    • @KeithThompson 感谢您证明您的反对意见。很多人没有!请参阅问题下的 cmets,我向 OP 询问了这个问题。他回答了这个link。但是,如果您想建议我如何改进我的答案,请告诉我!
    • @gsmaras 感谢您的帮助,但这不起作用。
    • @user3088049 与 wcstok() 相同?
    • 做了一些调整,效果很好,谢谢!
    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多