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

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

  连续最长的数字串的长度


一开始,我的代码是:

#include <stdlib.h>
#include <oj.h>

unsigned int Continumax(char** pOutputstr,  char* intputstr)
{
	unsigned int count = 0;
	unsigned int temp_count = 0;
	int k;
	char *p;
	char *temp = NULL;
	char *temp_out = NULL;
	p  = intputstr;
	*pOutputstr = (char *)malloc(100*sizeof(char));
	if(intputstr == NULL || *intputstr == '\0')
	{
		*pOutputstr = "";
		return count;
	}
	while(*p != '\0')
	{
		if(*p >= '0' && *p <= '9')
		{
			temp = p;
			while(*p >= '0' && *p <= '9')
			{
				++temp_count;
				++p;
			}
		}
		else
		{
			if(temp_count >= count)
			{
				count = temp_count;
				temp_out = temp;
			}
			temp_count = 0;
			++p;
		}
	}
	if(temp_count >= count)
	{
		count = temp_count;
		temp_out = temp;
	}
	for(k = 0; k < count; ++k)
		(*pOutputstr)[k] = temp_out[k];
	(*pOutputstr)[k] = '\0';
	return count;
}
调试时,当测试用例为 NULL 或者 空字符串时总是会出现以下错误(其它测试用例都正常):


费了一番周折才了解,
*pOutputstr = ""; 这个语句在无形之中修改了指针的指向,使得在调用处 free 的时候指针所指的位置已经不是 malloc 时指针的位置,所以才会出现这种错误。修改之后,正确的代码如下:

#include <stdlib.h>
#include <oj.h>

unsigned int Continumax(char** pOutputstr,  char* intputstr)
{
	unsigned int count = 0;
	unsigned int temp_count = 0;
	int k;
	char *p;
	char *temp = NULL;
	char *temp_out = NULL;
	p  = intputstr;
	*pOutputstr = (char *)malloc(100*sizeof(char));
	if(intputstr == NULL || *intputstr == '\0')
	{
		**pOutputstr = '\0';
		return count;
	}
	while(*p != '\0')
	{
		if(*p >= '0' && *p <= '9')
		{
			temp = p;
			while(*p >= '0' && *p <= '9')
			{
				++temp_count;
				++p;
			}
		}
		else
		{
			if(temp_count >= count)
			{
				count = temp_count;
				temp_out = temp;
			}
			temp_count = 0;
			++p;
		}
	}
	if(temp_count >= count)
	{
		count = temp_count;
		temp_out = temp;
	}
	for(k = 0; k < count; ++k)
		(*pOutputstr)[k] = temp_out[k];
	(*pOutputstr)[k] = '\0';
	return count;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值