知识点5——字符串处理+映射

题目描述:
给定两个字符集合,一个为全量字符集,一个为已占用字符集。已占用的字符集中的字符不能再使用,要求输出剩余可用字符集。
输入描述:
输入为一个字符串,字符串中包含了全量字符集合已占用字符集,两个字符集使用@连接。@前的字符集合为全量字符集,@后的字符集合为已占用字符集。
输入:
a:3,b:5,c:2@a:1,b:2
输出:
a:2,b:3,c:2
核心代码如下:

#include <iostream>
#include <string>
#include <map>
#include <sstream>
#include <algorithm>

using namespace std;

bool isNum(char ch)
{
	return ch <= '9' && ch >= '0';
}

int main()
{
	
	map<char, int> cnt1, cnt2;
	string s;
	string str;
	
	cin >> s;
	bool flag = true;
	for (int i = 0; i<s.size(); i++)
	{
		if (s[i] == ',')
			continue;	
		else if (s[i] == '@')
		{
			flag = false;
			continue;
		}

		if (flag)  //@之前部分
		{
			string num_str;
			char ch = s[i];
			str += s[i];
			num_str = s.substr(i + 2, 1);
			i += 2;
			while (isNum(s[i + 1]))
			{

				num_str = num_str + s.substr(i + 1, 1);
				i++;
			}
			int num = 0;
			stringstream ss(num_str);
			ss >> num;  //将ss输出给num
			//cout << ch << " " << num << endl;
			cnt1.insert(make_pair(ch, num));
		}
		else  //@之后部分
		{
			string num_str;
			char ch = s[i];

			num_str = s.substr(i + 2, 1);
			i += 2;
			while (i + 1 < s.size() && isNum(s[i + 1]))  //i + 1 < s.size()边界条件很重要,不然会内存越界
			{

				num_str = num_str + s.substr(i + 1, 1);
				i++;
			}
			int num = 0;
			stringstream ss(num_str);
			ss >> num;   //将ss输出给num
			//cout << ch << " " << num << endl;
			cnt2.insert(make_pair(ch, num));
		}
		//i++;
	}
	//cout << str << endl;
	for (map<char, int>::iterator it = cnt2.begin(); it != cnt2.end(); it++)
	{
		char ch = it->first;
		int n = it->second;
		cnt1[ch] -= n;
	}
	//cout << str << endl;
	flag = true;
	map<char, int>::iterator it;
	for (int i = 0; i<str.size(); i++)
	{
		
		it = cnt1.find(str[i]);
		if (it->second != 0)
		{
			if (flag)
			{
				cout << it->first << ":" << it->second;
				flag = false;
			}
			else
				cout << "," << it->first << ":" << it->second;
		}
	}
	cout << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值