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?



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.