Jokes on me
Jokes on me

Reputation: 33

Store words in char array C language

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.

Upvotes: 0

Views: 2459

Answers (2)

VolAnd
VolAnd

Reputation: 6407

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

Upvotes: 3

Shashwat Kumar
Shashwat Kumar

Reputation: 5297

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.

Upvotes: 0

Related Questions