25.找出字符串中的最長數字串

 寫一個函數,它的原形是int continumax(char *outputstr,char *intputstr)功能:
在字符串中找出連續最長的數字串,並把這個串的長度返回,
並把這個最長數字串付給其中一個函數參數outputstr 所指內存。
例如:"abcd12345ed125ss123456789"的首地址傳給intputstr 後,函數將返回9,
outputstr 所指的值爲123456789

看了下答案好像有問題,裏面有返回局部變量,好像不對!

自已寫了代碼,經測試可以成功運行!

#include<iostream>
using namespace std;

int continumax(char * &outputstr,char *inputstr,int &maxlen)
{
	if(inputstr==NULL)
		return 0;
	char *p=NULL,*q=NULL;
	p=q=inputstr;
	while(*p!='\0')
	{
		if(!(*p>='0'&&*p<='9'))
			p++;
		else
		{
			q=p;
			int count=0;
			while(*p>='\0'&&*p<='9'&&*p!='\0')
			{
				count++;
				p++;
			}
			if(maxlen<count)
				maxlen=count;
		}

	}
	outputstr=new char[maxlen+1];
	for(int i=0;i<maxlen;i++)
	{
		outputstr[i]=q[i];
	}
	return maxlen;
}

int main()
{
	char str[]="abc12345ed1235ss123456789";
	cout<<strlen(str)<<endl;
	char *outputstr=NULL;
	int maxlen=0;
	cout<<continumax(outputstr,str,maxlen)<<endl;
	
	for(int i=0;i<maxlen;i++)
		cout<<outputstr[i];
}

如果要按題目的原型的話,定義全局變量就OK 了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章