習(xí)題11-3 計(jì)算最長(zhǎng)的字符串長(zhǎng)度 (15 分)
1. 題目摘自
https://pintia.cn/problem-sets/12/problems/361
2. 題目?jī)?nèi)容
本題要求實(shí)現(xiàn)一個(gè)函數(shù),用于計(jì)算有n個(gè)元素的指針數(shù)組s中最長(zhǎng)的字符串的長(zhǎng)度。
函數(shù)接口定義:
int max_len( char *s[], int n );
其中n個(gè)字符串存儲(chǔ)在s[]中,函數(shù)max_len應(yīng)返回其中最長(zhǎng)字符串的長(zhǎng)度。
輸入樣例:
4
blue
yellow
red
green
輸出樣例:
6
3. 源碼參考
#include <iostream>
#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;
}
int max_len(char *s[], int n)
{
int len;
int i;
char **p;
p = s;
len = strlen(*p);
for (i = 1; i < n; i++)
{
if (len < strlen(*(p + i)))
{
len = strlen(*(p + i));
break;
}
}
return len;
}