1170: 最长字符串(指针专题)

1170

要点: 赋值到字符串数组中strcpy 和字符串比较strcmp

题名: http://acm.zzuli.edu.cn/problem.php?id=1170

题目描述
输入多个字符串,输出最长字符串。要求定义并使用函数maxLenStr(),void maxLenStr(char *str[], int n, int *max){从字符串数组str中找出最长的一个字符串,并将其下标存入形参指针max所指内存。}
输入
输入有多行,每行一个字符串,每个字符串长度不超过80,输入最多不超过100行,用****作为结束输入的标志,该行输入不用处理。
输出
输出最长的一个字符串。
样例输入 Copy
`L love C programming
ACM/ICPC
study hard
****`
**样例输出 Copy
L love C programming**

1.先使用temp临时数组来判断是否是****

  • 如果是退出 不是则下一步

2.建立char *[100], 使用temp来malloc→char字符数组 “安全建立”

3.输入完毕后,开始比较数组中的长度 规则如下:

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

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#define MAX 100
using namespace std;
void maxLenStr(char *str[], int n, int *max){
	int i;
	int m=0;
	for(i=0;i<n;i++){
		if(strlen(str[m]) < strlen(str[i])){
			m = i;
		}
	}
	*max =m;
}
int main(void){
	//3.15.2
	char *str[100];
	char temp[80];
	int i;
	for(i=0;;i++){
		gets(temp);
		if(strcmp(temp,"****") == 0)
			break;
		str[i] = (char *)malloc(sizeof(char) *(strlen(temp)+1));
		strcpy(str[i],temp);
	}  //输入完毕
	//开始比较
	int max;
	maxLenStr(str,i,&max);
	printf("%s",str[max]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值