ZT 查找字符串中连续最长的数字串

查找字符串中连续最长的数字串

有俩方法,1)比较好理解一些。2)晦涩

 

1)

/*
功能:在字符串中找出连续最长的数字串,并把这个串的长度返回,
并把这个最长数字串付给其中一个函数参数outputstr所指内存。
例如:"abcd12345ed125ss123456789"的首地址传给intputstr后,
函数将返回9,outputstr所指的值为123456789
*/
#include <stdio.h>
int Findmaxlen(char *input,char *output);
void main()
{
	char input[]="abc123def123456ee123456789dd";
	char output[50]={0};
	int maxlen;
	maxlen=Findmaxlen(input,output);
	printf("the str %s\n",output);
	printf("the maxlen is %d \n",maxlen);
}
int Findmaxlen(char *input,char *output)
{
	char *in=input,*out=output,*temp,*final;
	int count=0,maxlen=0,i;

	while(*in!='\0')
	{
		if(*in>='0'&&*in<='9')
		{
		   count=0;
		   for(temp=in;*in>='0'&&*in<='9';in++)
				count++;

		   if(maxlen<count)
		   {
				maxlen=count;
				final=temp;  
		   }//if
		}//if
		in++;
	}//while

	for(i=0;i<maxlen;i++)
	{
	*out++=*final++;
	}

	*out='\0';
	return maxlen;
}

 linux:/work/ctest/interview$ ./1
the str 123456789
the maxlen is 9

 

2)

题目:写一个函数,它的原型是如下,在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr所指的内存。

int continuemax(char *outputstr, char *inputstr)

举例:intputstr被赋予"abcd12345ed125ss123456789",函数将返回9,outputstr所指的值为"123456789"。

答:

复制代码
#include "stdafx.h"
#include <iostream>

using namespace std;

//查找字符串中连续最长的数字串
int continuemax(char *outputstr, char *inputstr)
{
    int maxLen = 0;
    char *pStart;
    char *maxStr;
    bool begin = true;
    int count = 0;
    while (*inputstr != '\0')
    {
        if (begin && isdigit(*inputstr))
        {
            pStart = inputstr;
            count++;
            begin = false;
        }
        else if (isdigit(*inputstr))
        {
            count++;
        }
        else
        {
            if (count > maxLen)
            {
                maxStr = pStart;
                maxLen = count;
            }
            count = 0;
            begin = true;
        }
        inputstr++;
        if (*inputstr == '\0' && count > maxLen)
        {
            maxStr = pStart;
            maxLen = count;
        }
    }
    *(maxStr + maxLen) = '\0';
    while(*maxStr != '\0')
    {
        *outputstr++ = *maxStr++;
    }
    *outputstr = '\0';
    return maxLen;
}


int _tmain(int argc, _TCHAR* argv[])
{
    char inputstr[] = "abcd12345ed125ss123456789";
    char *outputstr = new char[strlen(inputstr) + 1];
    memset(outputstr, 0, strlen(inputstr) + 1);
    cout<<continuemax(outputstr, inputstr)<<"  "<<outputstr<<endl;
    delete [] outputstr;
    return 0;
}
复制代码

运行界面如下:

分类: 算法面试

转载于:https://www.cnblogs.com/jeanschen/p/3550570.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值