Ma250
Ma250

Reputation: 357

Finding the longest string in a 2d array in C

I wrote a function that finds the longest string in a 2d array, it works, partially. My problem is that it takes the first longest string that it finds without checking the other ones.

For example, the following list of strings:

eke
em
ekeke
eme
e
ememeememe
emem
ekekee
eooeeeeefe
eede

My function catches "ekeke" (the third string from the list) as the longest instead of "ememeememe ".

Here is my function:

void length(char str[][MAX])
{
    int i = 0;

    for(i = 1; i < LEN; i++)
    {
        if(strlen(str[i]) > strlen(str[i-1]))
        {
            if(strlen(str[i]) > strlen(str[i+1]))
            {
                printf("%s", str[i]);
                break;
            }
        }
    }
}

LEN is a constant, his value is 10.
MAX is a constant, his value is 50.
The strings are given by the user.

Thanks.

Upvotes: 1

Views: 4334

Answers (1)

P.P
P.P

Reputation: 121397

You are only comparing the previous and next strings. You need to check the lengths of all the strings.

void length(char str[][MAX])
{
    size_t longest = strlen(str[0]);
    szie_t j = 0;

    for(size_t i = 1; i < LEN; i++)
    {
        size_t len = strlen(str[i]);
        if(longest < len)
        {
           longest = len;
           j = i;
        }
   }
   printf("%s", str[j]);
}

I am assuming you have at least 1 string and handle corner cases (if user inputs less than LEN strings etc -- depends on how you fill the str with strings).

Upvotes: 2

Related Questions