读入一个字符串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 ///////////////////////////////

  

上一篇:【C#】让工具栏ToolStrip能触发焦点控件的Leave、Validating、DataError等事件以验证数据


下一篇:Android发送短信