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

题目:写一个函数,它的原型是如下,在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数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;
}

运行界面如下:

posted @ 2012-08-30 19:59  venow  阅读(7731)  评论(0编辑  收藏  举报