獲取字符串中的數字串

#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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章