Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Split TCHAR

Tags:

How can I split a TCHAR into other variables? Example:

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

So, msg.texto has the string "MOVE 10 12" and I want the variable comando[50] to be "MOVE", the variable arg1 to be "10" and the variable arg2 to be "12". How can I do that? Sorry for some possible English mistakes. Thanks in advance!

SOLVED:

TCHAR *pch;
    pch = _wcstok(msg.texto, " ");
        _tcscpy(comando, pch);
        pch = _wcstok(NULL, " ");
        _tcscpy(arg1, pch);
        pch = _wcstok(NULL, " ");
        _tcscpy(arg2, pch);
like image 984
user3088049 Avatar asked May 14 '16 22:05

user3088049


1 Answers

For TCHAR, you could use strtok, like in this example:

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

In case it is a wchar_t, then you could use wcstok():

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

like image 143
gsamaras Avatar answered Sep 28 '22 03:09

gsamaras