題目:寫一個函數,它的原型是如下,在字符串中找出連續最長的數字串,並把這個串的長度返回,並把這個最長數字串付給其中一個函數參數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; }
運行界面如下: