#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