Method 1:- C program to separate words  from a given string

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

int main() {
   char string[50] = "welcome to the programming world";
   // Extract the first token
   char * token = strtok(string, " ");
   // loop through the string to extract all other tokens
   while( token != NULL ) {
      printf( " %s\n", token ); //printing each token
      token = strtok(NULL, " ");
   }
   return 0;
}

output:-

 welcome
 to
 the
 programming
 world

Method 2:-

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[100];
    char newString[10][10]; 
    int i,j,ctr;
       printf("\n\n Split string by space into words :\n");
       printf("---------------------------------------\n");    
 
    printf(" Input  a string : ");
    fgets(str1, sizeof str1, stdin);	
 
    j=0; ctr=0;
    for(i=0;i<=(strlen(str1));i++)
    {
        // if space or NULL found, assign NULL into newString[ctr]
        if(str1[i]==' '||str1[i]=='\0')
        {
            newString[ctr][j]='\0';
            ctr++;  //for next word
            j=0;    //for next word, init index to 0
        }
        else
        {
            newString[ctr][j]=str1[i];
            j++;
        }
    }
    printf("\n Strings or words after split by space are :\n");
    for(i=0;i < ctr;i++)
        printf(" %s\n",newString[i]);
    return 0;
}
output:-

 Split string by space into words :
---------------------------------------
 Input  a string : hello c programming begineer

 Strings or words after split by space are :
 hello
 c
 programminbegineer

 begineer

Method 3:-C program to separate words  from a given string by (-) stroke

// A C/C++ program for splitting a string
// using strtok()
#include <stdio.h>
#include <string.h>

int main()
{
	char str[] = "hello world";

	char *token = strtok(str, " ");

	while (token != NULL)
	{
		printf("%s-", token);
		token = strtok(NULL," ");
	}

	return 0;
}
output:-

hello-world

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post