0

I have this code:

char *pch;
pch = strtok(texto," ");

while (pch != NULL)
{
  pch = strtok (NULL, " ");
}

My "texto" variable have something like "This is my text example".

And i need to store each value comming from pch in while, in an array of characteres, but i really dont know how to do it.

I need something like that, each value in array will have a word, so:

"This is my text example".

Array[0][20] = This;

Array[1][20] = is;

Array[2][20] = my;

Array[3][20] = text;

Array[4][20] = example;

The pch in while having all these words already split, but I don't know how to add into a char array, or how I will declare him too.

danglingpointer
  • 4,708
  • 3
  • 24
  • 42

2 Answers2

3

Consider the following example:

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

#define MAXSTRLEN 20
#define MAXWORD 6

int main(void)
{
    char arr[MAXWORD][MAXSTRLEN+1] = {0};
    char str[] ="This is my text example";
    char *pch;
    int i = 0;
    pch = strtok (str," ");
    while (pch != NULL && i < MAXWORD)
    {
        strncpy(arr[i++], pch, MAXSTRLEN);
        pch = strtok (NULL, " ");
    }
    return 0;
}
VolAnd
  • 6,367
  • 3
  • 25
  • 43
  • Recommend `while (pch != NULL)` --> `while (i < 6 && pch != NULL)` – BLUEPIXY Jun 04 '17 at 18:38
  • 1
    @BLUEPIXY Yes, good suggestion - MAXWORD added to define number of token. – VolAnd Jun 05 '17 at 07:43
  • 3
    I've always liked `for (pch=strtok(str," "); i < MAXWORD && pch; pch=strtok(NULL, " \n")) strncpy(arr[i++], pch, MAXSTRLEN);` Either is fine, with the `for` you handle the initial and all subsequent calls in the one expression of the loop. – David C. Rankin Jun 05 '17 at 07:51
0

This should work. Use strcpy to copy pch to character array.

char str[] ="This is my text example";
char *pch;
int i = 0;
pch = strtok (str," ");
char a[10][20];
while (pch != NULL)
{   
  strcpy(a[i++], pch);
  pch = strtok (NULL, " ");
}

And as @stackptr has suggested dont use strtok and instead use strtok_r . For more info on this.

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66