Finding the longest string in a 2d array in C

前端 未结 1 439
南旧
南旧 2021-01-25 09:21

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 othe

相关标签:
1条回答
  • 2021-01-25 09:41

    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).

    0 讨论(0)
提交回复
热议问题