Write a programme to find out the longest word in a string.
Asked in/Preparing for : tcs
Reputation : 406


2 Responds



#include
#include
#include
int main()
{
    char string[100], word[20], max[20], min[20], c;
    int i = 0, j = 0, flag = 0;
 
    printf("Enter string: ");
    i = 0;
    do
    {
        fflush(stdin);
        c = getchar();
        string[i++] = c;
     } while (c != 'n');
     string[i - 1] = '0';

     for (i = 0; i < strlen(string); i++)
     {
           while ( i < strlen(string) && string[i] != " " && string[i] != '0' )
           {
                word[j++] = string[i++];
           }

           if (j != 0)
          {
                word[j] = '0';
                if (!flag)
                {
                      flag = !flag;
                      strcpy(max, word);
                      strcpy(min, word);
                }
                if (strlen(word) > strlen(max))
                {
                      strcpy(max, word);
                }
                if (strlen(word) < strlen(min))
               {
                      strcpy(min, word);
               }
               j = 0;
          }
     }
printf("The largest word is '%s' and smallest word is '%s' in '%s'.n", max, min, string);
return 0;
}
Manoj Sharma
Reputation : 221



#include <stdio.h>
#include <string.h>
#define LENGTH 20
int read_line(char str[], int n);
main()
{
    char largest[LENGTH];
    char smallest[LENGTH]; /* is the size of array okay */
    char input[LENGTH];
    int len;
    printf("Enter word: ");
    read_line(input, LENGTH);
    len = strlen(input);
    strcpy(smallest, input);
    strcpy(largest, input);
    if (len == 4){
         printf("nnTime to quitnn");
    }
    for ( ; ; ) {
        printf("Enter word: ");
        read_line(input, LENGTH);
        len = strlen(input); /* where do I use 'len' to find */
                                    /* shortest and longest */
                                   /* input and print those out ?? */
       if (strcmp(input, smallest) < 0) /* is this correct code for */
              strcpy(smallest, input); /* sorting alphabetically */
       else if (strcmp(input, largest) > 0)
             strcpy(largest, input);
       if (len == 4) break; /* is this necessary operation */
    }
    printf("nnnYou input four-letter wordn);
    printf("So time to quit.nn");
    printf("Smallest word: %sn", smallest);
    printf("Largest word: %sn", largest);
    return 0;
}
 
 
int read_line(char str[], int n)
{
     char ch;
     int i = 0;
     while ((ch = getchar()) != 'n')
     if (i < n)
     str[i++] = ch;
     str[i] = '0';
     return i;
}
Hardik Mehta
Reputation : 261



Written
Exam Questions
BLOG Posts
For study materials
Job Walk-In
Updates across India
Interview round
Questions
Interview or procedure
Experiences
Files
For study materials
Please LIKE our page to Get regular JOB WALK-IN UPDATES across India and STUDY MATERIALS on facebook news feed.