11-3 计算最长的字符串长度

该博客介绍了一个C语言编程问题,要求编写一个函数max_len来计算给定指针数组中存储的n个字符串的最长长度。通过使用strlen函数获取每个字符串的长度并比较,最终返回最长字符串的长度。提供的裁判测试程序展示了如何读取字符串数组并调用此函数。在输入样例中,给定四个颜色名称,输出为最长字符串'yellow'的长度,即6。

本题要求实现一个函数,用于计算有n个元素的指针数组s中最长的字符串的长度。

函数接口定义:

int max_len( char *s[], int n );

其中n个字符串存储在s[]中,函数max_len应返回其中最长字符串的长度。

裁判测试程序样例:

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

#define MAXN 10
#define MAXS 20

int max_len( char *s[], int n );

int main()
{
    int i, n;
    char *string[MAXN] = {NULL};
    
    scanf("%d", &n);
    for(i = 0; i < n; i++) {
        string[i] = (char *)malloc(sizeof(char)*MAXS);
        scanf("%s", string[i]);
    }
    printf("%d\n", max_len(string, n));

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

4
blue
yellow
red
green

输出样例:

6

这道题是计算最长的字符串长度,我们可以不计算每一个字符的长度,我们可以用l=strlen(s)的方法得到每一个字符串的长度,然后再进行比对,最后输出

int max_len( char *s[], int n ){
    int l,max=0;
    for(int i=0;i<n;i++){
        l=strlen(s[i]);   //直接求得长度
        if(l>max)  //与max比对
            max=l;
    }
    return max;
}
### 计算一组字符串中最大字符串长度的方法 对于给定的一组字符串,可以通过遍历这些字符串并记录其中最长字符串长度来解决问题。这里提供了一个Python实现方法: ```python def find_max_length(strings): """计算一组字符串中的最大字符串长度""" max_length = 0 for string in strings: stripped_string = string.lstrip() # 去除前导空格 current_length = len(stripped_string) if current_length > max_length: max_length = current_length return max_length ``` 此函数`find_max_length`接收一个字符串列表作为参数,并返回该列表中最长字符串的实际字符数(不计前导空格)。通过循环迭代每一个字符串,去除其前面可能存在的空白字符后测量剩余部分的长度,从而更新当前已知的最大长度。 考虑到不同编程语言的具体语法差异,在C语言环境下可以采用如下方式处理相同逻辑[^3]: ```c #include <stdio.h> #include <string.h> int max_len(char *str[], int n) { int max_length = strlen(str[0]); int i; for (i = 0; i < n; ++i) { while (*str[i] && isspace(*str[i])) str[i]++; // 跳过前导空格 int length_without_leading_spaces = strlen(str[i]); if (length_without_leading_spaces > max_length) { max_length = length_without_leading_spaces; } } return max_length; } int main() { int n = 4; char *strings[] = {" blue", " yellow ", "red", "\tgreen"}; printf("The maximum string length is %d.\n", max_len(strings, n)); return 0; } ``` 上述代码展示了如何忽略每个输入字符串开头可能出现的一个或多個空格,进而准确找出不含前导空格情况下最长的那个字符串长度
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值