C++ 提取字符串中的所有数字

上代码

例:

源数据 : a10b123cc45啊4859

解析后:10 123 45 4858

#include<list>
#include<vector>
#include<string>
#include<iostream>
using namespace std;

list<int> GetStringByNumArr(string str);

int main()
{
	while (true)
	{
		cout << "请输入字符串" << endl;
		string str;
		cin >> str;
		list<int> nums = GetStringByNumArr(str);

		for (list<int>::iterator it = nums.begin(); it != nums.end(); it++)
		{
			cout << *it << endl;
		}
	}

	system("pause");
	return 0;
}

char numarr[] = {
	'0',
	'1',
	'2',
	'3',
	'4',
	'5',
	'6',
	'7',
	'8',
	'9',
};

list<int> GetStringByNumArr(string str) {

	list<int> numlist;
	int startIndex = 0;

	while (startIndex != -1)
	{
		vector<char> tempnum;

		startIndex = -1;

		for (size_t i = 0; i < str.length(); i++)
		{
			for (size_t j = 0; j < (sizeof(numarr) / sizeof(numarr[0])); j++)
			{
				if (str[i] == numarr[j])
				{
					startIndex = i;
					break;
				}
			}

			if (startIndex != -1)
			{
				tempnum.push_back(str[startIndex]);
				int tempindex = 0;

				//向下查找数据
				char tempchar = str[startIndex + (tempindex += 1)];

				//表示为数字
				while (int(tempchar - 48) >= 0 && int(tempchar - 48) <= 9)
				{
					tempnum.push_back(tempchar);
					tempchar = str[startIndex + (tempindex += 1)];
				}

				//删除查询到的数据
				str.erase(startIndex, tempindex);
				break;
			}
		}
		
		if (!tempnum.empty()) {
			//cout << "tempnum : " << string(tempnum.begin(), tempnum.end()) << endl;
			numlist.push_back(stoi(string(tempnum.begin(), tempnum.end())));
		}
	}

	return numlist;
}

 

 

  • 5
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惊悚的毛毛虫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值