Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 decade ago

Longest String c program?

Okay this got me confused. How should I use the String Operation here?

You want a program that reads a list of strings until the word “end” appears (I can do the end bit easy), and returns the

longest string that was included in the input list (confused now)

So, for example if the input is:

“God”, “this”, “is”, “boring”, “end”

output will be:

“The longest string is: boring”

And if there are several strings of the same length, return the first one (confused here as well)

3 Answers

Relevance
  • Anonymous
    1 decade ago
    Favorite Answer

    Hm....

    qsort() method prototype in stdlib.h

    Ex: List of array are "ca", "bcar", "cab", "ciapr", "canused".

    #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

    int des_sort_function( const void *a, const void *b);

    int asc_sort_function( const void *a, const void *b);

    char list[5][10] = { "ca", "bcar", "cab", "ciapr", "canused" };

    int main(void)

    {

    int x;

    printf("\n\n\n");

    qsort((void *)list, 5, sizeof(list[0]), des_sort_function);

    for (x = 0; x < 5; x++)

    printf("%s\n", list[x]);

    printf("The longest string is: %s",list[x-1]);

    printf("\n\n\n");

    qsort((void *)list, 5, sizeof(list[0]), asc_sort_function);

    for (x = 0; x < 5; x++)

    printf("%s\n", list[x]);

    printf("The longest string is: %s",list[0]);

    return 0;

    }

    int des_sort_function( const void *a, const void *b)

    {

    if(strlen(a)<strlen(b))return -1;

    else if(strlen(a)==strlen(b))return 0;

    else return 1;

    }

    int asc_sort_function( const void *a, const void *b)

    {

    if(strlen(a)<strlen(b))return 1;

    else if(strlen(a)==strlen(b))return 0;

    else return -1;

    }

  • 1 decade ago

    Only store the new string if its length is greater than the previous string.

    At the end of the loop print the stored string.

    Have fun.

  • 1 decade ago

    include<stdio.h>

    #include<string.h>

    main()

    {

    char *str, newstr[100];

    while(1)

    {

    scanf("%s",newstr);

    if(strcmp(newstr,"end")==0)

    break;

    else

    {

    if(strlen(newstr)>strlen(str))

    str=newstr;

    }

    }

    printf("%s",str);

    }

Still have questions? Get your answers by asking now.