String operations are often used in the written examination and interview of companies of all sizes. The goal of the "string operation series" is to sort out common string operation questions and provide the author's reference code. I will keep updating this series of blog posts, so stay tuned!
Question: Write a function. Its prototype is int continumax (char * outputstr, char * intputstr)
Function: Find the longest consecutive numeric string in the string, return the length of the string, and pay the longest numeric string to the memory specified by one of the function parameters outputstr.
For example, after the first address of "abcd12345ed125ss123456789" is passed to intputstr, the function returns 9 and the Value indicated by outputstr is 123456789.
Analysis: if the length of the input string is N, an integer array count with the size of N is allocated. Count [I] records the maximum continuous numeric string length before the I character in the original string. Count [I] has the following recursive relationship:
Count [I] = count [I-1] + 1, when the I-th character is a number,
Count [I] = 0, when the I character is not a number.
Now, the C/C ++ source code is posted below:
# Include <iostream> # include <assert. h> using namespace STD; int continumax (char * outputstr, char * intputstr) {assert (null! = Outputstr & null! = Intputstr); int Len = strlen (intputstr); int * COUNT = new int [Len]; int max = 0; char * P = intputstr; For (INT I = 0; I <Len; I ++) {count [I] = 0; If (* (p + I)> = '0' & * (p + I) <= '9') {If (0 = I) {count [I] = 1;} else {count [I] = count [I-1] + 1 ;} if (count [I]> count [Max]) {max = I ;}} char * t = P + max-count [Max] + 1; for (INT I = 0; I <count [Max]; I ++) {* outputstr ++ = * (t + I) ;}* outputstr = '\ 0 '; max = count [Max]; // pay attention to releasing memory to prevent memory leakage Delete [] count; return Max;} int main () {char * STR = "abcd12345ed125ss123456789 "; char * digitstr = new char [strlen (STR) + 1]; cout <continumax (digitstr, STR) <Endl; cout <STR <Endl; cout <digitstr <Endl; return 0 ;}
The source code execution result is as follows: