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

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

https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec

//先确定连续最长的数字串长度,再通过长度确定数字串起点和终点位置。
//数组也是指针,学会用下标确定输出字符区间。
#include <stdio.h>
#include <string.h>

int main() {
    char str[201] = {0};
    
    while(scanf("%s", str) != EOF)
    {
       int len = strlen(str);
       int n = 0, max = 0;
       for(int i = 0; i<len; i++){
            if(str[i] >= '0' && str[i] <= '9') 
                n++;
            else  //用此可以省略continue
                n = 0;
            if(n>max)
                max = n;            
       }
       for(int i=0; i<len; i++) //多用一个循环解决存在输出多个满足条件的数字串
       {
            if(str[i] >= '0' && str[i] <= '9') //i,j两个变量作判断
            {
                int j = i+1;
                while( str[j] && str[j] >= '0' && str[j] <= '9' )
                {
                    j++;
                }
                if(j-i == max)
                {
                    while(j!=i) //这里i,j决定了数字串的位置区间
                        printf("%c", str[i++]);
                }
                else {
                    i=j; //继续往后判断数字串长度
                }
            }
       }
        printf(",%d\n", max);
        
    }
    return 0;
}

全部评论

相关推荐

karis_aqa:和hr没关系,都是打工的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务