问题描述
试题编号: | 201403-3 |
试题名称: | 命令行选项 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 请你写一个命令行分析程序,用以分析给定的命令行里包含哪些选项。每个命令行由若干个字符串组成,它们之间恰好由一个空格分隔。这些字符串中的第一个为该命令行工具的名字,由小写字母组成,你的程序不用对它进行处理。在工具名字之后可能会包含若干选项,然后可能会包含一 些不是选项的参数。 输入格式 输入的第一行是一个格式字符串,它至少包含一个字符,且长度不超过 52。格式字符串只包含小写字母和冒号,保证每个小写字母至多出现一次,不会有两个相邻的冒号,也不会以冒号开头。 输出格式 输出有 N 行。其中第 i 行以"Case i:" 开始,然后应当有恰好一个空格,然后应当按照字母升序输出该命令行中用到的所有选项的名称,对于带参数的选项,在输出它的名称之后还要输出它的参数。如果一个选项在命令行中出现了多次,只输出一次。如果一个带参数的选项在命令行中出 现了多次,只输出最后一次出现时所带的参数。 样例输入 albw:x 样例输出 Case 1: -a -l |
#include <iostream>
#include <sstream>
#include <map>
using namespace std;
int type[26] = {0}; //
int main() {
string s, str, t;
int n;
cin >> s >> n;
getchar();
//对参数预处理
for (int i = 0; i < s.length(); i++) {
if (s[i + 1] == ':') {
type[s[i] - 'a'] = 2; //有参
i++;
}
else {
type[s[i] - 'a'] = 1; //无参
}
}
for (int i = 0; i < n; i++) {
getline(cin, str);
map<char, string> ans;
//把字符串以空格分隔
stringstream ss(str);
ss >> s; // 读入名称
while (ss >> s) {
if (s.size() == 2) { //符合参数要求
if (s[0] == '-' && type[s[1] - 'a'] == 1) { //无参
ans[s[1]] = "";
}
else if (s[0] == '-' && type[s[1] - 'a'] == 2) { //有参
if (ss >> t) { //输入参数
ans[s[1]] = t;
}
else break;
}
else break;
}
else break;
}
printf("Case %d: ", i + 1);
for (map<char, string>::iterator it = ans.begin(); it != ans.end(); it++) {
printf("-%c ", it->first);
if (it->second != "") printf("%s ", it->second.c_str());
}
printf("\n");
}
return 0;
}