• 计算最长的字符串长度


    输入n (n<10)个字符串,输出其中最长字符串的有效长度。要求自定义函数 Int max_len ( char *s[],int n),用于计算有n个元素的指针数组s中最长的字符串的长度。

    法一:
    思路:设置一个指针数组与一个二维数组,使指针数组指向二维数组
    #include<stdio.h>
    #include<string.h>
    int max_len(char*s[],int n)
    {
    int i,j=0;
    for(i=0;i<n;i++)
    {
    if(strlen(s[i])>strlen(s[j]))
    {
    j=i;
    }
    }
    return strlen(s[j]);
    }
    int main()
    {
    int i,n;
    char*s[10];
    char a[10][10];
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    scanf("%s",a[i]);
    s[i]=a[i];
    }
    printf("%d",max_len(s,n));

    }

    法二:
    思路:利用动态分配,malloc,只有一个指针数组
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    int max_len(char*s[],int n)
    {
    int max=0;
    int i;
    for(i=0;i<n;i++)
    {
    if(strlen(s[max])<strlen(s[i]))
    {
    max=i;
    }
    }
    return strlen(s[max]);
    }
    int main()
    {
    int n;
    int i;
    char*str[10];
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    str[i]=(char*)malloc(sizeof(char)*10);/*这边本来想用strlen(str)+1的,不知道为什么会出错,用了这种方法,只能运行,但效率低下*/
    scanf("%s",str[i]);
    }
    printf("%d ",max_len(str,n));
    return 0;
    }

  • 相关阅读:
    WINFORM 設計時 未能加载文件或程序集問題解決
    Remove row from generic datatable in C#(The given DataRow is not in the current DataRowCollection)
    questa.sim in the linux
    the io_printf
    how to search new file in linux
    the rld control core
    window's chkdsk
    tq
    the init state machine
    brazen out
  • 原文地址:https://www.cnblogs.com/zhouweibaba/p/10127814.html
Copyright © 2020-2023  润新知