Split a string into words
C program to split a string into words.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void split_words(char str[MAX], char words[MAX][MAX])
{
int i, j, count;
char prev_char;
i = 0;
j = 0;
count = 0;
prev_char = '\0';
while(1)
{
if(str[i] == ' ' || str[i] == '\t' || str[i] == '\0')
{
if(prev_char!=' ' && prev_char!='\t' && prev_char!='\0')
{
words[count][j] = '\0';
count++;
j = 0;
}
}
else
{
words[count][j] = str[i];
j++;
}
prev_char = str[i];
if(str[i] == '\0')
break;
else
i++;
}
printf("\nwords After splitting are\n");
for(i=0;i<count;i++)
{
puts(words[i]);
}
}
void main()
{
char str[MAX];
char words[MAX][MAX];
printf("Enter the string\t:");
gets(str);
split_words(str, words);
getch();
}
Output
Enter the string :welcome to www.coursecrux.com. Happy Coding!!
words After splitting are
welcome
to
www.coursecrux.com.
Happy
Coding!!