0
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...

1
  • in TCL, we can do by splitting the line [split $line " "] and then all words ll be in list elements. Is there any similar procedure in C? Commented Feb 20, 2016 at 8:31

2 Answers 2

3

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++; 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Since you properly initialize your b array, to iterate over all strings copied to the array (presuming you always leave b[4]... empty) , you can iterate over the strings with while (*b[i]) printf( "b[%d] = %s\n", i, b[i] ); (you can do the same with a dynamically allocated array of pointers-to-char by insuring you realloc before assigning a value to the last pointer).
No, you already initialized all characters to 0 with char b[5][20] = {{0}};, so simply checking whether the first char is something other than 0 allows you to avoid the additional call to strlen :) -- try it, replace your entire print loop with the while (*b[i]) loop. (you do need to insure you set i = 0; before the loop and i++ at the end)
Give it a try i = 0; while (*b[i]) { printf( "b[%d] = %s\n", i, b[i] ); i++; }
0

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, " ,.-");   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.