简体   繁体   中英

How to create an array of strings from a given line in C?

char a[100]="You are welcome";

Now how can I make the words in this line into array of strings?

char b[5][20];
strcpy(b[0],"you");
strcpy(b[1],"are");
strcpy(b[2],"welcome");

In this way, we can make array of strings.

But I want to do dynamically for any giving input ?

Please help...

strtok is your friend:

char a[] = "You are welcome";
char b[5][20] = {{0}};
char *pch;

pch = strtok( a," \t" );
int i = 0;
while( NULL != pch && i < 5)
{
    strcpy(b[i++], pch);
    pch = strtok( NULL, " \t\n" );
}

for( i = 0; i < 5; i++ )
{
    if( strlen(b[i]) > 0 )
    {
        printf( "b[%d] = %s\n", i, b[i] );
    }
}

Don't forget to #include <string.h>


As David C. Rankin pointed out. We can do away with strlen by just checking the first char not \\0 . So this'd be a better solution (note that the main while loop for strtok processing remains the same).

i = 0; 
while (*b[i]) 
{ 
    printf( "b[%d] = %s\n", i, b[i] ); 
    i++; 
}

Reference:strtok

You can go for a "scanf" in place of "printf" inside while loop, and store the values in second array(b in your case)

 while (pch != NULL)   {
     printf ("%s\n",pch);
     pch = strtok (NULL, " ,.-");   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM