简体   繁体   English

打印出c中最长的字符串

[英]print out the longest string in c

Given any number of program parameters input into the command-line, calculate the length of each one, and lastly output the longest string. 在命令行中输入任意数量的程序参数后,计算每个参数的长度,最后输出最长的字符串。 Here is my code, but it seems to be wrong. 这是我的代码,但这似乎是错误的。

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

int main(int argc, char *argv[]) {
  size_t maxlen = 0, len;
  int i;
  int longest;


  for (i = 1; i < argc; i++) {
   len = strlen(argv[i]);
     if (len > maxlen) 
       longest = argv[i];
  }

  printf("The longest string is %s. \n", longest);

  return 0;
}

Mistakes: 误区:

One. 一。 char max; ... max = strlen(argv[i]); wrong; 错误; strlen() returns size_t and not a char . strlen()返回size_t而不是char

Two: if(max < argv[i]) also wrong, you're comparing the length of the string with a pointer to the string. 二: if(max < argv[i])也是错误的,您正在将字符串的长度与指向该字符串的指针进行比较。 That doesn't even make sense. 那甚至没有意义。 What you probably want is 您可能想要的是

size_t maxlen = 0, len;
int i, maxindex = 0;

for (i = 1; i < argc; i++) {
    len = strlen(argv[i]);
    if (len > maxlen) {
        maxlen = len;
        maxindex = i;
    }
}

printf("The longest string is '%s'\n", argv[maxindex]);

Your problem is in here: 您的问题在这里:

max = strlen(argv[i]);
if(max < argv[i])
{
  max=argv[i];
}

You seem to be a bit confused about what max is for here. 您似乎对这里的max有点困惑。 What you really want to do is: 您真正想要做的是:

  • take strlen(argv[i]) , and store it in a variable strlen(argv[i]) ,并将其存储在变量中
  • check whether it is greater than max 检查是否大于max
  • if it is, store it in max 如果是,将其存储在max

Try translating that to C code and post what you come up with. 尝试将其翻译为C代码,然后发表您的想法。

Did you mean: 你的意思是:

int i;
int max = strlen(argv[0]);

for (i = 0; i < argc; ++i) 
{
    if (max < strlen(argv[i]))
    {
        max = strlen(argv[i]);
    }
}
int max = 0;//assuming  initial max length of 0. start loop from index 1 (index 0 is program name)
for(i = 1; i < argc; ++i) {

    int len = strlen(argv[i]);//get length of str
    if(max < len )
    {
       max=len;//store the new max length
    }
}

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

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