声明
这是 拼题A(PTA)《中M2019秋C入门和进阶练习集》的习题。原题在 https://pintia.cn/problem-sets/1163286449659043840/problems/1174288506294865934 (侵删)
本人的答案仅供交流学习,请勿用于当作答案来提交!
题目描述
6-15 计算最长的字符串长度 (15 point(s))
本题要求实现一个函数,用于计算有n个元素的指针数组s中最长的字符串的长度。
函数接口定义:
1 2 | int max_len( char *s[], int n ); |
其中n个字符串存储在s[]中,函数max_len应返回其中最长字符串的长度。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #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
我的答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | /*================================================================ * Copyright (C) 2019 Navin Xu. All rights reserved. * * Filename :6-15-计算最长的字符串长度.c * Author :Navin Xu * E-Mail :admin@navinxu.com * Create Date :2019年10月10日 * Description : ================================================================*/ #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; } // 以下是有效代码 int max_len( char *s[], int n ) { size_t max_len = 0; for (int i = 0; i < n; i ++) { if (strlen(s[i]) > max_len) max_len = strlen(s[i]); } return max_len; } |
© 2019, wpmaster. All rights reserved.
鉴于本人的相关知识储备以及能力有限,本博客的观点或者描述如有错漏或是有考虑不周到的地方还请多多包涵,也欢迎指正,一起学习,共同进步。
0