问题描述:
输入一串字符串,提取其中的键值对
输入:输入一串字符串,以等号和逗号隔开
输出:输出按指定的格式如实例
示例:
输入:
name=Justin,age=18,gender=male,job=swe
输出: [[name,Justin],[age,18],[gender,male],[job,swe]]
下面参考程序是在VS2013中调试的:
// 提取键值对.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<cstdlib>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string str;
char ch;
vector<string> svec;
while (getline(cin, str))
{
istringstream sin(str);
int i = 0;
int j = 0;//记录等号个数
int temp1 =0, temp2 =0;//记录位置
string s1;
while (sin >> ch)
{
if (ch == '=')//提取键
{
temp1 = i;
if (temp2 < temp1)
{
if (temp2 ==0)
s1 = str.substr(0, temp1);
else
s1 = str.substr(temp2 + 1, temp1 - temp2 - 1);
svec.push_back(s1);
}
else//键为空
{
s1 = "";
svec.push_back(s1);
}
j++;
}
if (ch == ',')//提取值
{
temp2 = i;
if (temp2 > temp1)
{
s1 = str.substr(temp1 + 1, temp2 - temp1 - 1);
svec.push_back(s1);
//cout << s1;
}
else//键值为空
{
s1 = "";
svec.push_back(s1);
}
}
i++;
}
//提取最后一个值
if (temp1 < str.size())
{
s1 = str.substr(temp1 + 1, str.size() - temp1);
svec.push_back(s1);
//cout << s1;
}
else//键值为空
{
s1 = "";
svec.push_back(s1);
}
for (int i = 0; i < svec.size(); i += 2)
{
if (i == 0)
cout << "[[" << svec[i] << "," << svec[i + 1] << "],";
else if (i/2 == j-1)
cout << "[" << svec[i] << "," << svec[i + 1] << "]]" <<endl;
else
cout << "[" << svec[i]<<","<< svec[i+1] << "],";
}
svec.clear();
}
system("pause");
return 0;
}