字串中找出連續最長的數字串,返回找到的字串和長度
阿新 • • 發佈:2020-12-28
題目描述: 請一個在字串中找出連續最長的數字串,並把這個串的長度返回;如果存在長度相同的連續數字串,返回最後一個連續數字串; 注意:數字串只需要是數字組成的就可以,並不要求順序,比如數字串“1234”的長度就小於數字串“1359055”,如果沒有數字,則返回空字串(“”)而不是NULL! 樣例輸入 abcd12345ed125ss123058789 abcd12345ss54761 樣例輸出 輸出123058789,函式返回值9 輸出54761,函式返回值5 介面說明 函式原型: unsignedint Continumax(char** pOutputstr, char* intputstr) 輸入引數: char* intputstr 輸入字串; 輸出引數: char** pOutputstr: 連續最長的數字串,如果連續最長的數字串的長度為0,應該返回空字串;如果輸入字串是空,也應該返回空字串; 返回值: 連續最長的數字串的長度
程式碼實現
#include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <cstring> //function unsigned int Continumax(char** poutputstr,const char* pinputstr) { unsigned int str_len = strlen(pinputstr); char* pContinuStr = new char[str_len+1]; unsigned int len_max = 0,len_cur = 0; const char* pslow = pinputstr; const char* pfast = pinputstr; if(NULL == pinputstr) { strncpy(pContinuStr," ",str_len); *poutputstr = pContinuStr; return 0; } while(*pslow !='\0') { if(*pslow >='0' && *pslow <= '9') { while(*pfast >='0' && *pfast <= '9') { len_cur++; pfast++; } if(len_cur>0 && len_max<len_cur) { memset(pContinuStr,'\0',str_len+1); strncpy(pContinuStr,pslow,len_cur); cout<<pContinuStr<<endl; len_max = len_cur; } len_cur = 0; pslow = pfast; } else { pslow++; pfast++; } } *poutputstr = pContinuStr; return len_max; } //test int main(void) { const char *pinputstr="abcd12345ed125ss123058789"; char *poutputstr = NULL; unsigned int len = 0; len = Continumax(&poutputstr,pinputstr); cout<<"len="<<len<<" str="<<poutputstr<<endl; system("pause"); delete [] poutputstr; poutputstr = NULL; return 0; }
驗證結果: