The instance code that finds the longest continuous string of Numbers in a string
- 2020-04-02 01:34:16
- OfStack
//1. Write a function whose subtype is int continumax(char *outputstr,char *intputstr).
//Function:
//Find the longest string of consecutive digits in the string and return the length of the string,
//The longest number is passed in a string to the memory of one of the function arguments outputstr.
//For example: "abcd12345ed125ss123456789", after the first address to intputstr function returns 9, outputstr referring value is 123456789
#include<stdio.h>
#include<assert.h>
int continumax(char *outputstr,char *inputstr)
{
assert(outputstr);
assert(inputstr);
int length = 0;
int maxlength = 0;
int i = 0;
int j = 0;
while(inputstr[i] != '0')
{
while( inputstr[i] >='0'&& inputstr[i] <= '9')
{
length++;
i++;
}
if(length > maxlength)
{
maxlength = length;
int k = i-maxlength;
for(j = 0; j < maxlength; j++ )
{
outputstr[j] =inputstr[k++];
}
length = 0;
continue;
}
i++;
length = 0;
}
outputstr[j] = '0';
return maxlength;
}
int main( )
{
char inputstr[ ]= "abcd12345eddafsd125ss123456789";
char outputstr[100];
int max_numstr_length = continumax(outputstr,inputstr);
printf("%sn",outputstr);
printf("the max_numstr_length is %dn", max_numstr_length);
return 0;
}
#include<iostream.h>
#include<malloc.h>
int continumax(char * outputstr, char * inputstr)
{
int len = 0; //The length of the statistics string
int max = 0; //The length of the current maximum number string
char *pstr =NULL; //Records the starting position of the maximum numeric character
while(* inputstr!= '0')
{
if(*inputstr <= '9' && *inputstr >='0') //The length of the statistics substring
{
len++;
inputstr++;
continue;
}
else if (len > max) //Updates if the number string is greater than the length of the current maximum number substring
{
max = len;
pstr = inputstr-len;
len = 0;
}
inputstr++;
}
for(int i = 0 ; i<max;i++) //Copy the value of the largest substring to outputstr
{
*outputstr = *pstr;
outputstr++;
pstr++;
}
outputstr = outputstr-max;
outputstr[max] ='0';
cout<<outputstr<<endl;
return max;
}
int main()
{
char input[] = "de1234de123456ed";
//char * out = (char *)malloc(100*sizeof(char));
char output[100];
int max = continumax(output, input);
cout<<max<<endl;
return 0;
}