Home » Code Snippets » C/C++ Code Snippets

C program to split string into the words separated by spaces

By: IncludeHelp On 06 DEC 2016

In this program, we are taking a string and splitting the string into the words (separated by the spaces).

For example there is a string “This is Mike” and string will be stored into two dimensional character array (string array) the values will be “This”, “is”, “Mike”.

To implement this program we are taking a two dimensional character array (string array), this array will store maximum 10 words with maximum 20 characters.

Function which is using to extract words from the string

int getWords(char *base, char target[10][20])
  • int n - is the return type which will return total number of extracted words.
  • char *base - is the base string, from this string we will extract the words.
  • char target[10][20] - is the two dimensional character array (string array) that will store the extracted words.

Extract words from a string separated by space in c programming

#include <stdio.h>
#define TRUE 1

//this function will get the string array
//and split into the words, seprated by spaces

int getWords(char *base, char target[10][20])
{
	int n=0,i,j=0;
	
	for(i=0;TRUE;i++)
	{
		if(base[i]!=' '){
			target[n][j++]=base[i];
		}
		else{
			target[n][j++]='\0';//insert NULL
			n++;
			j=0;
		}
		if(base[i]=='\0')
		    break;
	}
	return n;
	
}
int main()
{
	int n; //number of words
	int i; //loop counter 
	char str[]="This is Mike";
	char arr[10][20];
	
	n=getWords(str,arr);
	
	for(i=0;i<=n;i++)
		printf("%s\n",arr[i]);
	
	return 0;
}

Output

    This
    is
    Mike

Program will read the string character by character (loop condition is infinite); there are two conditions which are checking inside the loop. First if character is not space then character is storing into the two dimensional character array and second, if it is space or NULL; a NULL character is storing to terminate the newly created strings.

There is another condition to check the NULL, if there is NULL within the loop, loop will be terminated and retuned n (number of created words).



Comments and Discussions!

Load comments ↻





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