要求:
讀入一個長度不超過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 ///////////////////////////////
