简体   繁体   English

在C中的2d数组中找到最长的字符串

[英]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. 我编写了一个函数,该函数可以在2d数组中找到最长的字符串,但它可以部分工作。 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 ke
em EM
ekeke ke
eme me
e Ë
ememeememe 词素
emem em
ekekee ekekee
eooeeeeefe eoeeeeeefe
eede 伊迪

My function catches "ekeke" (the third string from the list) as the longest instead of "ememeememe ". 我的函数以最长的时间捕获“ ekeke”(列表中的第三个字符串),而不是“ 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. LEN是一个常数,他的值是10。
MAX is a constant, his value is 50. MAX是一个常数,他的值为50。
The strings are given by the user. 字符串由用户给出。

Thanks. 谢谢。

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). 我假设您至少有1个字符串并处理转角情况(如果用户输入的字符数少于LEN字符串等-取决于您如何用字符串填充str )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM