-2

Hey I'm currently learning c language. Is there any possibility to turn char* type variable, which contains some words separated by spaces into an array of string(in c it's char*[]) that way that each word on the original variable will be in different index in the new array?

timrau
  • 22,578
  • 4
  • 51
  • 64
user2559696
  • 111
  • 1
  • 8

1 Answers1

1

C library Function strtok():

char * strtok ( char * str, const char * delimiters );

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ");
  while (pch != NULL)
  {
     printf ("%s\n",pch);
     pch = strtok (NULL, " ");
  }

  return 0;
}
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
  • But I thought there isn't a string type on c language?.. and in the first example can you edit it that way that it will put the tokens into an array of chars? – user2559696 Oct 05 '13 at 16:02
  • yep it divides the char[] based on the delimiter you provided to the function. For further info please visit the link – Umer Farooq Oct 05 '13 at 16:07
  • You splitted array into tokens. I asked to spilt (char*) type to array. – user2559696 Oct 05 '13 at 16:14
  • @UmerFarooq: the "manual method" does not make any sense as it copies every character of `str` to `tokens`. The OP asked for splitting `char *str` to `char *array[numTokens]` or so. – harpun Oct 05 '13 at 16:15
  • @harpun yep at first I thought it was C++ question so I used string in place of char[], later removed that. thanks for pointing that out :) – Umer Farooq Oct 05 '13 at 16:16