H面试程序(6):字符串中找出连续最长的数字串

 

 

//1. 写一个函数,它的原形是int continumax(char *outputstr,char *intputstr)
//功能:
//在字符串中找出连续最长的数字串,并把这个串的长度返回,
//并把这个最长数字串付给其中一个函数参数outputstr所指内存。
//例如:"abcd12345ed125ss123456789"的首地址传给intputstr后,函数将返回9,outputstr所指的值为123456789
#include<stdio.h>
#include<assert.h>
int continumax(char *outputstr,char *inputstr)
{   
	assert(outputstr);
    assert(inputstr);
	int length = 0;
	int maxlength = 0; 
	int i = 0;
	int j = 0;
    while(inputstr[i] != '\0')
	{
		while( inputstr[i] >='0'&& inputstr[i] <= '9')
		{   
			length++;
			i++;
		}
		if(length > maxlength)
		{
			maxlength = length;
			int k = i-maxlength;
			for(j = 0; j < maxlength; j++ )
			{  
				
				outputstr[j] =inputstr[k++];
				
			}
			length = 0;
			continue;
		}
		i++;
		length = 0;
	}
	    outputstr[j] = '\0';
		return maxlength;
}



int main( )
{   
    char inputstr[ ]= "abcd12345eddafsd125ss123456789";
	char outputstr[100];

    int max_numstr_length = continumax(outputstr,inputstr);
	printf("%s\n",outputstr);
	printf("the max_numstr_length is %d\n", max_numstr_length);
	return 0;
}


 

 

ii

 

#include<iostream.h>
#include<malloc.h>


int continumax(char * outputstr, char * inputstr)
{
	int len = 0;        //统计数字字符串的长度
	int max = 0;        //当前最大数字字符串的长度
	char *pstr =NULL;   //记录最大数字字符的起始位置


	while(* inputstr!= '\0')
	{
		if(*inputstr <= '9' && *inputstr >='0')  //统计数字子字符串的长度
		{
			len++;
			inputstr++;
			continue;
		}
		else if (len > max)        //如果统计出来的数字字符串大于当前的最大数字子字符串的长度,则更新
		{
			max = len;
			pstr = inputstr-len;      
			len = 0;
		}
		inputstr++;
	}
	for(int i = 0 ; i<max;i++)  //将最大子字符串的值拷贝给outputstr
	{
		*outputstr = *pstr;
        outputstr++;
	    pstr++;
	}
	
	   outputstr = outputstr-max;
	   outputstr[max] ='\0';
	   cout<<outputstr<<endl;

	   return max;

	
}

int main()
{
	char input[] = "de1234de123456ed";
	//char * out = (char *)malloc(100*sizeof(char));
	char output[100];
	int max = continumax(output, input);
	cout<<max<<endl;
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值