zoukankan      html  css  js  c++  java
  • 查找字符串中连续最长的数字串

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

    运行界面如下:

  • 相关阅读:
    bootmgr is missing
    【转】ahci和IDE的区别
    win10系统故障代码:0xc000014c
    c++小数点后舍入
    关于类里再声明自身类实例的思考
    Java集合
    Python图片转字符画
    102. Binary Tree Level Order Traversal
    1041. Robot Bounded In Circle
    144. Binary Tree Preorder Traversal
  • 原文地址:https://www.cnblogs.com/venow/p/2663706.html
Copyright © 2011-2022 走看看