C语言实现查找字符串中最大的数字子串

题目

请编写程序,主函数中输入一行字符串,内有数字字符和非数字字符,调用函数求该字符串中数字字串最大的数字,并在主函数中显示最大的数字,限定该字符串中数字字串最多不超过10个。

实现代码

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define N 100
int findmax(char* s, float* pmax);//定义的功能函数,传地址对其max修改
void main(void)
{
	char array[N];//输入的字符串
	char temp[N];//中转字串
	int i;
	float max = 0;
	puts("please input a string");
	gets_s(array);
	if (findmax(array, &max) == 0)//空串
		printf("no number in the string
");
	else
		printf("maximum number is %g", max);
}
int findmax(char* s, float* pmax)
{
	int findflag = 0,flag=0,no=0,tempcnt=0;//flag用于判断现在读到的数字的位置
	char* p,temp[10];//p指针访问数组,temp存储字串
	for (p = s;*p != ;p++)
	{
		if (*p >= 0 && *p <= 9 || *p == .)
		{
			flag = 1;
			temp[tempcnt++] = *p;//将字符存储
		}
		else if (flag == 1)
		{
			flag = 0;
			findflag = 1;
			temp[tempcnt] = ;//数字字串结束后补‘’
			tempcnt = 0;
			number++;//数字字串个数
			if (number == 1)
			{
				*pmax = atof(temp);//atof函数可以直接将字符串转换为浮点数
			}
			else
			{
				if (atof(temp) > *pmax)
				{
					*pmax = atof(temp);//设标签排序法
				}
			}
		}
	}
	if (flag == 1)//如果最后一个还是数字的处理
	{
		temp[tempcnt] = ;
		number++;
		if (number == 1)
			*pmax = atof(temp);
		else
		{
			if (atof(temp) > *pmax)
				*pmax = atof(temp);
		}
	}
	return findflag;
	

}
经验分享 程序员 微信小程序 职场和发展