查找字符串中连续最长的数字串
有俩方法,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; }
运行界面如下:
分类: 算法面试