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

本文介绍了一个用于查找字符串中连续最长数字串的C语言函数。该函数能够找到并返回最长连续数字串及其长度,适用于文本处理等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

功能:在字符串中找出连续最长的数字串,并把这个串的长度返回
函数原型:
   unsigned int Continumax(char** pOutputstr,  char* intputstr)
输入参数:
   char* intputstr  输入字符串
输出参数:
   char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串
   pOutputstr 指向的内存应该在函数内用malloc函数申请,由调用处负责释放

返回值:
  连续最长的数字串的长度
#include <stdlib.h>

int main()
{
	unsigned int Continumax(char** ,  char* );
	//char inStr[] = "abcd12345ed125ss123058789";
	char inStr[] = "abcd12345ss54761";
	//char inStr[] = "fdjndkjyjrthd";
	char *OutStr;
	int nOut = 0;

	nOut = Continumax(&OutStr,inStr);

	return 0;
}

unsigned int Continumax(char** pOutputstr,  char* intputstr)
{
	char *pIn = NULL;
	int i = 0, nIn = 0;
	int curCnt = 0,maxCnt = 0,curPos = 0;
	pIn = intputstr;

	while (*pIn != NULL)
	{
		nIn ++;
		pIn++;
	}
	int nInpnew = nIn+1;
	pIn = (char *)malloc(nInpnew*sizeof(char));

	for (i=0;i<nIn;i++)
	{
		pIn[i] = intputstr[i];
	}

	for (i=0;i<nIn;i++)
	{
		if ((pIn[i]>='0')&&(pIn[i]<='9'))
		{
			curCnt += 1;
		}
		if (!((pIn[i+1]>='0')&&(pIn[i+1]<='9')))
		{
			if (maxCnt <= curCnt)
			{
				curPos = i+1;
				maxCnt = curCnt;
			}
			if (pIn[i+1] != '\0')
			{
				curCnt = 0;
			}
		}		
	}

	if (maxCnt == 0)
	{
		*pOutputstr = (char *)malloc(0*sizeof(char));
		(*pOutputstr)[0] = '\0';
		free(pIn);
		return 0;
	}

	*pOutputstr = (char *)malloc(maxCnt*sizeof(char));
	for (i=0;i<maxCnt;i++)
	{
		(*pOutputstr)[i] = pIn[curPos-maxCnt+i];
	}
	(*pOutputstr)[i] = '\0';
	free(pIn);

	return maxCnt;
}
这个写法很笨,还有很大改进空间,待改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值