C++分离字符串中的数字和字符

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

void part(string _str, vector<int> &_num, vector<char> &_op)
{
	int sum = 0;
	unsigned int i = 0;

	while (i < _str.length())
	{
		if ('0' <= _str.at(i) && _str.at(i) <= '9')
			//还原连续的数字
			sum = sum * 10 + (_str.at(i) - '0');
		else
		{
			_num.push_back(sum);
			_op.push_back(_str.at(i));
			sum = 0;
		}
		i++;
	}
	
	//判断最后一个字符是否是数字
	if (0 != sum)
		_num.push_back(sum);
}

int main()
{
	vector<int> num(0);
	vector<char> op(0);
	string str;

	cin >> str;
	part(str, num, op);

	//输出测试
	for (unsigned int i = 0; i < num.size(); i++)
		cout << num.at(i) << " ";
	cout << endl;
	for (unsigned int i = 0; i < op.size(); i++)
		cout << op.at(i) << " ";

    return 0;
}

输入:

1+6+1/4+5*3

输出:

1 6 1 4 5 3
+ + / + *
    原文作者:白水baishui
    原文地址: https://blog.csdn.net/baishuiniyaonulia/article/details/80322184
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞