Find the largest and smallest word in a string
C program to find the largest and smallest word in a string.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50
int 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++;
}
return(count);
}
void main()
{
char str[MAX];
char words[MAX][MAX];
int count, i, j;
int max_len, min_len;
printf("Enter the string\t:");
gets(str);
count = split_words(str, words);
max_len = strlen(words[0]);
min_len = strlen(words[0]);
for(i=0;i<count;i++)
{
if(strlen(words[i]) < min_len)
{
min_len = strlen(words[i]);
}
if(strlen(words[i]) > max_len)
{
max_len = strlen(words[i]);
}
}
printf("\nsmallest word in the string\t:");
for(i=0;i<count;i++)
{
if(strlen(words[i]) == min_len)
{
printf("%s\t",words[i]);
}
}
printf("\nlargest word in the string\t:");
for(i=0;i<count;i++)
{
if(strlen(words[i]) == max_len)
{
printf("%s,\t",words[i]);
}
}
getch();
}
Output
Enter the string :this is a test string happy coding
smallest word in the string :a
largest word in the string :string, coding,