读入一个字符串str,输出字符串str中连续最长的数字串

要求:

读入一个长度不超过256的字符串,例如“abc123defg123456789hjfs123456”。要求输出“123456789”

 

思路:

遍历字符串,如果是数字串则计算往后一共有多少个数字,计算出数字的开头与长度添加的容器中,往后继续读取;

遍历完字符串后遍历容器中存储的长度最长的Value。

 

具体代码如下:

/************************************************************************/
/* Project:			输出字符串中连续最长的数字串							*/
/* Author:														*/
/* Time:			2017/10/03											*/
/* Description:		读入一个字符串str,输出字符串str中连续最长的数字串		*/
/************************************************************************/

#include "stdafx.h"
#include <iostream>
#include <ctype.h>
#include <vector>
using namespace std;

char* GetLongestNumber(char* pBuf, size_t nSize, char** pNum);


//


int _tmain(int argc, _TCHAR* argv[])
{
	char* pBuf = new char[128];
	memset(pBuf, 0, sizeof(char)* 128);
	cin.getline(pBuf, 128);
	char* pNum = NULL;
	GetLongestNumber(pBuf, 128, &pNum);
	if (pNum)
		cout << "The longest number is:" << pNum << endl;
	else cout << "Cannot find Longest number string." << endl;

	delete[] pBuf;
	pBuf = NULL;
	system("pause");
	return 0;
}


//


typedef struct data
{
	char* p;
	int nLength;
	data()
	{
		p = NULL;
		nLength = 0;
	}
}DATA, *LPDATA;


//


char* GetLongestNumber(char* pBuf, size_t nSize, char** pNum)
{
	if (!pBuf || nSize <= 0 || !pNum)return NULL;
	vector<DATA> vect;
	DATA da;

	// 遍历字符串
	for (int i = 0; i < strlen(pBuf); i++)
	{
		if (isdigit(*(pBuf + i)))
		{
			// 往后查找数字字符
			int nCount = i;
			while (isdigit(*(pBuf + nCount)))
				nCount++;
			da.p = pBuf + (i - 1);
			da.nLength = nCount - (i - 1);
			vect.push_back(da);	// 插入相关信息到vector中
			da.p = NULL; 
			da.nLength = 0;
			i = nCount;
		}
		i++;
	}

	// 计算Vector中.nLength最大的元素
	auto it = vect.end() -1;
	DATA Max = *it;
	it--;
	while (it >= vect.begin())
	{
		if (it->nLength > Max.nLength)
			Max = *it;
		if(it != vect.begin())it--;
		else break;
	}

	// 得到最长的数字串
	*pNum = new char[Max.nLength + 1];
	memset(*pNum, 0, sizeof(char)* Max.nLength + 1);
	memcpy(*pNum, Max.p, Max.nLength);
	return *pNum;
}


 End of File ///

  

转载于:https://www.cnblogs.com/LandyTan/p/7636136.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值