求最长的数字字符串

写一个函数,它的原形是:

int continumax(char *outputstr,char *intputstr)

功能:

在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr所指内存。

例如:
"abcd12345ed125ss123456789"的首地址传给intputstr后,函数将返回9,outputstr所指的值为123456789。

注意很多答案是错的,未考虑末尾不是字母的情况!

int countintmax(char* input, char* output)
{
    int max_len = 0;
    int max_start = 0;
    int len = 0;
    char* ptr = input;
    while(*ptr!='
int countintmax(char* input, char* output)
{
    int max_len = 0;
    int max_start = 0;
    int len = 0;
    char* ptr = input;
    while(*ptr!='\0')
    {   
        if(*ptr>='0' && *ptr<='9')
        {   
            len++;
        }else
        {   
            if(len>max_len)
            {   
                max_len = len;
                max_start = ptr-input-len;
            }   
            len = 0;
        }   
        ptr++;
    }   
    // Last may be 0~9, then not judeged len
    if(len>max_len)
    {   
        max_len = len;
        max_start = ptr-input-len;
    }   
    if(max_len!=0)
    {   
        memcpy(output, &input[max_start], max_len);
        output[max_len] = '\0';
    }   
    return max_len;
}

int main()
{
    char* str = "abcd12345ed125ss123456789"; // 9 123456789
    char buf[1024];
    printf("%s\n%d %s\n", str, countintmax(str, buf), buf);
    return 0;
}
') { if(*ptr>='0' && *ptr<='9') { len++; }else { if(len>max_len) { max_len = len; max_start = ptr-input-len; } len = 0; } ptr++; } // Last may be 0~9, then not judeged len if(len>max_len) { max_len = len; max_start = ptr-input-len; } if(max_len!=0) { memcpy(output, &input[max_start], max_len); output[max_len] = '
int countintmax(char* input, char* output)
{
    int max_len = 0;
    int max_start = 0;
    int len = 0;
    char* ptr = input;
    while(*ptr!='\0')
    {   
        if(*ptr>='0' && *ptr<='9')
        {   
            len++;
        }else
        {   
            if(len>max_len)
            {   
                max_len = len;
                max_start = ptr-input-len;
            }   
            len = 0;
        }   
        ptr++;
    }   
    // Last may be 0~9, then not judeged len
    if(len>max_len)
    {   
        max_len = len;
        max_start = ptr-input-len;
    }   
    if(max_len!=0)
    {   
        memcpy(output, &input[max_start], max_len);
        output[max_len] = '\0';
    }   
    return max_len;
}

int main()
{
    char* str = "abcd12345ed125ss123456789"; // 9 123456789
    char buf[1024];
    printf("%s\n%d %s\n", str, countintmax(str, buf), buf);
    return 0;
}
'; } return max_len; } int main() { char* str = "abcd12345ed125ss123456789"; // 9 123456789 char buf[1024]; printf("%s\n%d %s\n", str, countintmax(str, buf), buf); return 0; }

Leave a Reply

Your email address will not be published. Required fields are marked *