题解 | #字符串中找出连续最长的数字串#

字符串中找出连续最长的数字串

https://www.nowcoder.com/practice/bd891093881d4ddf9e56e7cc8416562d

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
    char str[256] = {0};
    gets(str); // 接收输入
    int max = 0; // 最长数字串的长度
    char maxstr[256] = {0}; // 保存最长数字串
    for (int i = 0; i < strlen(str);) { // 遍历输入的字符串
        if (isdigit(str[i])) { // 如果当前字符是数字字符
            int count = 0; // 记录这一次得到的连续数字的个数
            char tmp[256] = {0}; // 保存这次得到的连续数字串
            int j = 0; // tmp数组的索引
            while (isdigit(str[i])) {
                ++count; // 当前字符是数字字符,则计数器递增1
                tmp[j] = str[i]; // 保存当前的数字字符
                ++j; // tmp的索引递增1
                ++i; // i递增1
            }
            // 如果本次得到的连续数字个数大于当前的最大值,则更新当前最大值,并更新最长数字串
            if (count > max) {
                max = count; // 更新当前最大值
                strcpy(maxstr, tmp); // 更新最长数字串
            }

        } else { // 如果当前字符不是数字字符,则直接遍历下一个字符
            ++i;
        }
    }
    puts(maxstr); // 输出最终保存的最长数字串
    return 0;
}

全部评论

相关推荐

祈求顺利毕业😁:简历很好了,多投吧牛油😂。主要是环境不好,大家也卷
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务