ADVERTISEMENT
ADVERTISEMENT

C - Split String into Words using C programs.


IncludeHelp 16 August 2016

In this code snippet we will learn how to split string into words?

For example we have a string "Hello friends how are you?" this string will be spelt into words "Hello", "friends", "how", "are", "you?". And these words will be assigned into string array and then we can use them as separate strings.

C Code Snippet – Split String into Words in C

/*C - Split String into Words using C programs.*/

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

int main(){
	char text[100]={0};
	//assume there may be 5 words of
	//20 characters maximum
	char split[5][20]={0};
	int i,j,k;
	
	printf("Enter text: ");
	fgets(text,100,stdin);
	
	j=0;k=0;
	for(i=0;i<strlen(text);i++){
		
		if(text[i]==' '){
			if(text[i+1]!=' '){
				split[k][j]='\0';
				j=0;
				k++;
			}
			continue;
		}
		else{
			//copy other characters
			split[k][j++]=text[i];
		}		
	}
	split[k][j]='\0';
	
	//print split strings
	
	
	for(i=0;i<=k;i++){
		printf("%s\n",split[i]);
	}
	
	return 0;	
}
    Enter text: Hello friends how are you?
    Hello
    friends
    how
    are
    you?

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.