Home » C programs » C String User Defined Functions

C program to split string by space into words

In this C program, we are going to learn how to split a given string by spaces and storing the substring in an array of strings.

Example:

Input string: “Hello how are you?"

Output:
"Hello"
"how"
"are"
"you?"
/*C program to split string by space into words.*/
#include <stdio.h>
#include <string.h>

int main()
{
	char str[100];
	char splitStrings[10][10]; //can store 10 words of 10 characters
	int i,j,cnt;

	printf("Enter a string: ");
	gets(str);

	j=0; cnt=0;
	for(i=0;i<=(strlen(str));i++)
	{
		// if space or NULL found, assign NULL into splitStrings[cnt]
		if(str[i]==' '||str[i]=='\0')
		{
			splitStrings[cnt][j]='\0';
			cnt++;	//for next word
			j=0;	//for next word, init index to 0
		}
		else
		{
			splitStrings[cnt][j]=str[i];
			j++;
		}
	}
	printf("\nOriginal String is: %s",str);
	printf("\nStrings (words) after split by space:\n");
	for(i=0;i < cnt;i++)
		printf("%s\n",splitStrings[i]);
	return 0;
}
  

Output

    Enter a string: Hello Guys This is a test string.

    Original String is: Hello Guys This is a test string.
    Strings (words) after split by space:
    Hello
    Guys
    This
    is
    a
    test
    string.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.