您的位置:首页 > 编程语言 > C语言/C++

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

2016-11-28 22:54 344 查看
在字符串中找出连续最长的数字串,并把这个串的长度返回,如果是个空串则返回“ ”;

例如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++;
      


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 编程 字符串