每日一题:华为初级题库——在字符串中找出连续最长的数字串

  耽搁了许久,就不说废话,直接上题了。

  <题目要求>

    在字符串中找出连续最长的数字串,并把这个串的长度返回;函数原型:

unsigned int Continumax(char** pOutputstr,  char* intputstr),后者是输入字符串,前者是输出的连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串,而非NULL。pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放(此话的意思是free(pOutputstr);在下载工程包中的main函数已写,不用在该函数中实现。没有该包的童鞋,就自行在main函数实现free吧)。

  思路:遍历输入的字符串的每一位,遇到数字后就开始循环计算其的长度,当遇到的不是数字后,就开始跳出这个循环,将记录与保存的最大长度变量进行比较,更新最大长度变量。

  易错点分析:在函数中返回字符串,要利用指针的指针对其重新分配内存空间,并将数值拷贝到分配的内存空间。不能直接将最长数字串的起始位置的指针赋给返回字符串指针的位置。

  此处给出的是完整小程序版本。

#include <iostream>
#include<stdlib.h>
using namespace std;
unsigned int Continumax(char** pOutputstr,  char* inputstr)
{
    int tmpnum=0,j=0,tmp=0,tmpend;
    while(inputstr[j]!='')
    {
        tmpnum=0;
        while('0'<=inputstr[j]&&inputstr[j]<='9')
        {
            tmpnum++;
            j++;
        }
        if(tmpnum>=tmp)
        {
            tmp=tmpnum;
            tmpend=j-1;
        }
        j++;
    }
    if(0==tmp)
    {

        *pOutputstr=(char*)malloc(sizeof(char));
        **pOutputstr='';

        return 0;
    }
    else
    {
        *pOutputstr=(char*)malloc(sizeof(char)*tmp);
        //cout<<"begin is:"<<tmpend-tmp+1<<endl<<"num is"<<tmp<<endl;//检测用
        *pOutputstr=inputstr+tmpend-tmp+1;
        return tmp;
    }
}
int main()
{
    char a[100];
    cin>>a;
    char *b;
    int i=Continumax(&b,a);
    //检测显示最长字符串
//    cout << "Hello world! i= "<<i << endl;
//    int j=0;
//    if(b[j]=='')
//        cout<<"right>"<<b[j]<<"<";
//    while(b[j]!='')
//    {
//        cout<<b[j]<<endl;
//        j++;
//    }
    free (b);
    return 0;
}
原文地址:https://www.cnblogs.com/Sophie-nature/p/3671188.html