用c语言求字符串中的最大的数怎么求

实现寻找字符串中的最大数字。(假设数字全部为正整数。)
如"123ty#342 rre 99/*9"
求出342
急!!!!!

#include "stdio.h"

int main()
{
    char s[100];
    int n, max;
    char *cp;

    gets(s);

    cp = s;
    n = 0;
    max = 0;
    while(*cp != '\0')
    {
        if(*cp >= '0' && *cp <= '9')
        {
            n = n*10 + *cp - '0';
        }
        else
        {
            if(max < n)
                max = n;
            n = 0;
        }
        cp++;
    }
    if(max < n)
        max = n;

    printf("max is %d\n", max);

    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-05
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

unsigned long max_num(const char *str) {
    unsigned long max = 0UL, i;
    static const char num_string[] = "0123456789";
    const char *cur = strpbrk(str, num_string);
    while (cur != NULL) {
        if ((i = strtoul(cur, &str, 10)) > max) max = i;
        cur = strpbrk(str, num_string);
    }
    return max;
}

int main(void) {
    printf("%lu\n", max_num("123ty#342 rre 99/*9"));
    return 0;
}

第2个回答  2020-12-29

C语言字符串的学习,输入指定字符串,并且计算字符串的位数

相似回答