获取字符串中的数字串

#include <cstring>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
// 获取字符串中的数字串
void pickNum(const char* str, vector<char*>& numVec)
{
	// 验证参数有效性
	if(str == NULL || strlen(str) == 0)
	{
		cerr << "invalid parameter";
		return;
	}
	const char* start = str;
	while(*start != '\0')
	{
		// 定位到数字字符串的头
		while(*start != '\0' && (*start > '9' || *start < '0'))
		{
			++start;
		}
		const char* end = start;
		// 定位到数字字符串尾下一个字符
		while(*end != '\0' && *end >= '0' && *end <= '9')
		{
			++end;
		}
		if(*start != '\0')
		{
			int len = end - start;
			char* numStr = new char[len + 1];
			memcpy(numStr, start, len);
			numStr[len] = '\0';
			numVec.push_back(numStr);
		}
		start = end;
	}
}
int main(int argc, char* argv[])
{
	// 测试用例
	vector<const char*> strVec;
	strVec.push_back(NULL);
	strVec.push_back("");
	strVec.push_back("abc");
	strVec.push_back("a1b2c");
	strVec.push_back("a12b2c13");
	strVec.push_back("0a1b2c3");
	strVec.push_back("01234");
	for(int strIdx = 0; strIdx < strVec.size(); ++strIdx)
	{
		cout << strIdx << " : ";
		if(strVec[strIdx] != NULL)
		{
			cout << strVec[strIdx];
		}
		cout << " : ";
		vector<char*> numVec;
		pickNum(strVec[strIdx], numVec);
		for(int numIdx = 0; numIdx < numVec.size(); ++numIdx)
		{
			cout << numVec[numIdx] << ' ';
		}
		cout << endl;
	}
	return 0;
}

运行结果:

0 :  : invalid parameter
1 :  : invalid parameter
2 : abc : 
3 : a1b2c : 1 2 
4 : a12b2c13 : 12 2 13 
5 : 0a1b2c3 : 0 1 2 3 
6 : 01234 : 01234


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值