简体   繁体   English

在C中找到最长的单词

[英]Find Longest Word in C

I want to find longest string from array of strings by taking command line arguments. 我想通过采用命令行参数从字符串数组中找到最长的字符串。 I can receive command line arguments, but what's wrong with my logic? 我可以接收命令行参数,但是逻辑出了什么问题?

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {

    int i;
    char *c = argv[1];
    int maxSize = strlen(argv[1]);

    for(i=2;i<=argc;i++){
        int len = strlen(argv[i]);
        if(len>maxSize){
            maxSize = len;
            c = argv[i];
        }
    }

    printf("Max length string : %s", c);
}

Your loop is running out-of-array. 您的循环正在阵列外运行。

It seems you understand the meanings of argc and argv, but you missed that argc is the number of the input arguments including the name of the process. 似乎您了解argc和argv的含义,但是您错过了argc是输入参数的数量,包括进程的名称。

For the following input cases, you will receive 5 for argc and the last argument string, 'flow', is found in argv[4]. 对于以下输入情况,您将为argc收到5,最后一个参数字符串'flow'在argv [4]中找到。

a.out hello statck over flow a.out您好statck流量过大

However, your code will run into argv[5] which is not the part of argments, and can result in undefined behavior. 但是,您的代码将遇到argv [5],这不是argments的一部分,并且可能导致未定义的行为。

The loop in the code should be changed like, 代码中的循环应更改为

for(i=1; i<argc; i++)
{
}
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if (argc == 1) {
        printf("No arguments provided");
        return 1;
    }

    int maxLength = 0;
    int maxIndex = 0;

    int i;
    char* word;
    for (i = 1; i < argc; i++) {
        word = argv[i];
        int length = strlen(word);
        if (length > maxLength) {
            maxLength = length;
            maxIndex = i;
        }
    }

    printf("Max length is %d for string: %s\n", maxLength, argv[maxIndex]);
    return 0;
}

Here are some comments to your code, hope it helps. 这是您的代码的一些注释,希望对您有所帮助。

在此处输入图片说明

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

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