在字符串中找出连续最长数字串【经典】

在字符串中找出连续最长的数字串,并把这个串的长度返回,如果是个空串则返回“ ”;

例如sddsa12345asf123返回3;

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

unsigned int CountStr(char **outputStr, char *inputStr)
{
    if(NULL == inputStr || '\0' == inputStr)
    {
        *outputStr = "";
        return 0;
    }
    int inod = 0;
    int maxLenth = 0;
    int tmpLenth = 0;
    for(int i = 0; inputStr[i] != '\0'; i++)
    {
        if(inputStr[i] >= '0' && inputStr[i] <= '9')
        {
            tmpLenth++;
            if(tmpLenth >= maxLenth)
            {
                inod = i;
                maxLenth = tmpLenth;
            }
        }
        else
        {
            tmpLenth = 0;
        }
    }
    if(maxLenth <= 0)
    {
        *outputStr = "";
        return 0;
    }

    *outputStr = (char*)malloc(sizeof(char)*(maxLenth + 1));
    strncpy(*outputStr, inputStr + inod -maxLenth + 1, maxLenth);
    (*outputStr)[maxLenth] = '\0';
    return maxLenth;

}

int main()
{
    char b[100], c[100];
    int num;
    printf("请输入一个字符串\n");
    scanf("%s", b);
    char *a = c;
    num = CountStr(&a, b);
    printf("数字串的最大长度为%d",num);
    return 0;
}


注:我写的.cpp文件,已使用G++ [filename]编译运行。
       gcc原则上也是可以编译c++文件,但实际操作中并没有自动链接c++的库,即使.cpp文件不包含任何C++头文件或特有语句,编译输出时还是会报错,需编译命令加-lstdc++;
      





  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值