编程题:将一个字符串中连续最长的数字串打印出来

题目要求:写一个函数,原型为int continumax(char *outputstr,char *inputstr),功能:在字符串中 找出连续最长的数字串,并把这个串的长度返回,同时把这个最长的数字串付给其中一个参数outputstr所指内存,例如:"abcd12345ed125ss123456789aa"的首地址传给inputstr后,函数返回9,outputstr所指的值为123456789.

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;


int continumax(char *outputstr,char *inputstr)
{
	int len = strlen(outputstr);						//计算输入字符串长度
	char temp[1024] = {0};								//临时数组存放数字串
	int count = 0;
	int num = 0;
	for(int i = 0;i < len;i++)							//遍历输入字符串
	{
		if(outputstr[i] >= '0' && outputstr[i] <= '9')	//判断是否为数字,若是则开始计数
		{
			count++;
			if(i == len-1 && num < count)				//当输入字符串以数字结尾,且当前数字串长度比前数字串长,则更新count与temp
			{
				num = count;
				for(int j = 0;j < num;j++)
				{
					temp[j] = outputstr[i-num+j];
				}			
			}
		}
		else
		{
			if(num < count)								//当数字串结束,判断当前数字串长度是否比前数字串长,若是则更新count与temp
			{
				num = count;
				for(int j = 0;j < num;j++)
				{
					temp[j] = outputstr[i-num+j];
				}
			}			
			count = 0;									//count清零重新记录下个数字段长度
		}

	}
	inputstr = &temp[0];
	cout << inputstr << endl;
	return num;
}

int main()
{
	char *str = "abcd12345ed125ss123456789aa";
	char str1[1024] = {0};
	int num = 0;
	num = continumax(str,str1);
	printf("%d\n",num);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42720695/article/details/82960124